In JavaScript, there is no inheritance keyword: extends. So, what methods does it use to generate attributes (inherit/copy) based on another constructor when using a constructor to generate an object? That is: when using the new keyword on a function to generate an object, the properties of the object can come from other functions.
This article provides two ways of writing:
The first (informal):
But you need to understand this usage.
Javascript code
function Animal (name, age){
this.name = name;
this.age = age;
}
function Dog (name, age){
this .i = Animal;
this.i(name, age);
}
d = new Dog('hello',20);
console.log(d);
/*
Dog {name: "hello", age: 20}
age: 20
i: function Animal(name, age)
name: "hello"
__proto__:
constructor: function Dog(name, age)
*/
The above way of writing is to refer to the external function Animal as one of its own internal member functions.
This is a way of writing an anonymous function.
Equivalent to:
Javascript code
function Dog (name, age){
this.i = function Animal (name, age){
this.name = name;
This.age = age;
}
this.i(name, age);
}
Equivalent to:
Javascript code
function Dog (name, age){
/*
When calling a function, Instead of using the 'new' keyword to create
object,
// calling a function
animal ();
using the 'new' keyword to create object.
NEW A nimal ( );
The inner 'this' is the same one of the outer 'this'. Because
there is no 'this' object created inside of the function, so it has to refer to the outer one.
*/
this.i = function (name, age){
this.name = name; // 2. so the inner "this" is the same
This.age = age; // one of the outer "this".
}
this.i(name, age); // 1. function call, no 'this' created.
🎜}
Thinking: When calling a function, who is "this"? ?
Since, function call does not generate "this" object.
So isn’t it possible to call Animal directly within Dog?
Answer: No
Java Code
/*
Which 'this' the called function belongs to, the inner 'this' inside of
the called function referers to that 'this' object.
*/
function Dog (name, age){ // if call Animal directly,
Animal(name,age); // the Animal function here belongs to 'window',
} // so 'this' inside of Animal references to 'window'
Second (formal):
Use apply() function or call() function
apply() : apply "this" object to the(that) function, then call it.
Javascript code
function Animal (name, age){
this.name = name;
this.age = age;
}
function Do g (name, age){
Animal.apply(this, arguments); // apply "this" object to Animal function. // call Animal function with a given 'this' call Animal function with a given 'this' other 'this'.
}
d = new Dog('hello',20);
console.log(d);
/*
Dog {name: " hello", age: 20}
age: 20
name: "hello"
__proto__:
constructor: function Dog(name, age)
*/