web前端:理解js原型链

时间:2017-11-04 15:02:57 魔新豆网

工具/材料

  javascript

操作方法

  学习原型链之前我们先认识一下构造函数,代码如下:

function S() {
this.name = 'xxx';
this.say = function() { console.log(this.name) }
}
var s1 = new S();

其中,s1是S的实例,s1的__proto__(大家先不用管__proto__属性,后续会讲到)中有一个constructor(构造函数)属性,该属性指向S。
在这里,大家可以记住两点:
1.s1是构造函数S的实例;
2.s1.__proto__.constructor===S 也可以写成 s1.constructor===S;

web前端:理解js原型链

  接下来我们来看下一段代码:

function S2() {}
S2.prototype.name = 'XXX';
S2.prototype.say = function() {
console.log(this.name);
}

var s2 = new S2();
var s3 = new S2();
console.log(s2.sayName === s3.sayName);//true
console.log(s2.__proto__===S2.prototype);//true

这一段代码中我们可以看到一个新属性——prototype,这是什么呢,其实这就是构造函数S2的原型对象,每个对象都有__proto__属性,但是只有函数对象才有prototype属性。而s2是构造函数S2的实例,而s2.__proto__指向的就是S2的原型对象,即s2.__proto__===S2.prototype。得到一个结论,实例的__proto__属性指向的就是其构造函数的原型对象。

web前端:理解js原型链

  继续上一步的代码,我们添加代码继续调试:

console.log(s2.__proto__);//返回S2的原型对象
console.log(S2.prototype);//返回S2的原型对象

console.log(s2.__proto__.__proto__);//返回Object对象
console.log(S2.prototype.__proto__);//返回Object对象

console.log(s2.__proto__.__proto__.__proto__);//返回null
console.log(S2.prototype.__proto__.__proto__);//返回null

其实,S2的原型对象上还有原型对象,因为S2的原型对象也相当于只是Object对象的一个实例。

web前端:理解js原型链

  在这里我给大家画了一张图,便于大家理解原型链。

web前端:理解js原型链

  

特别提示

  码子不易,专家如有说得不对的地方,望大家指点包含,谢谢

本文标签: