Prototype
As you all know, JavaScript does not contain the traditional class inheritance model, but rather uses the prototype prototype model. The code implementation is probably like this.
?
123456789101112 |
function Student(name){
this
.name = name;
}
var Kimy =
new Student(
"Kimy"
);
Student.prototype.say =
function
(){
console.log(
this
.name +
"say"
);
}
Kimy.say();
//Kimysay
|
KimY itself has no say method, and when he does not find the method in his own object, he goes back to his prototype, that is, to find the Student.prototype object. Here we use a constructor student
constructors, __proto__, and prototype chains
In addition to Internet Explorer, other browsers have deployed a nonstandard __proto__ attribute (two underscores before and after) on an instance of the object object, which points to the prototype object, the prototype property of the constructor.
Stealing a piece of code and a graph
?
12345678910111213141516171819202122232425262728293031323334 |
// 构造方法
function Foo(y) {
this
.y = y;
}
Foo.prototype.x = 10;
// 继承方法"calculate"
Foo.prototype.calculate =
function (z) {
return this
.x +
this
.y + z;
};
// 使用foo模式创建 "b" and "c"
var b =
new Foo(20);
var c =
new Foo(30);
// 调用继承的方法
b.calculate(30);
// 60
c.calculate(40);
// 80
console.log(
b.__proto__ === Foo.prototype,
// true
c.__proto__ === Foo.prototype,
// true
b.constructor === Foo,
// true
c.constructor === Foo,
// true
Foo.prototype.constructor === Foo
// true
b.calculate === b.__proto__.calculate,
// true
b.__proto__.calculate === Foo.prototype.calculate
// true
);
|
As we can see, each object contains a __proto__ property, B's __proto__ points to the construction of construct B, the prototype property of Foo, and Foo.prototype is an object, and itself has a __proto__ A prototype that points to the construction method that constructs the object. Object.prototype's __proto__ is pointed to null, which forms a prototype chain.
This is a piece of code that can be understood here.
?
1234 |
Object instanceof Function //true Function instanceof Object //true |
What did new do?
There is also a small problem, JS inside the normal function and the form of the constructor does not seem to be much different (the initial capitalization is not necessary, but usually the first letter of the constructor is capitalized). What the new keyword has done.
Example
var kimy = new Student ();
New has done three things.
?
12345 |
var Kimy = {}; Kimy.__proto__ = Student.prototype; Student.call(Kimy); |
1. Define an empty object
2. Set its prototype
3. Initializing objects
This will understand why kimy.__proto__ points to Student.prototype (the same reference), which is the new one that plays a key role!
Understanding prototypes and prototype chains in JavaScript