理解JavaScript原型链

高洛峰
高洛峰 原创
2016-12-09 09:13:18 724浏览

每一个JavaScript对象都和另一个对象相关联,相关联的这个对象就是我们所说的“原型”。每一个对象都会从原型继承属性和方法。有一个特殊的对象没有原型,就是Object。在之后的图示中会进行说明。

举个栗子,我们首先声明一个函数Student():

function Student(name){
  this.name = name;
 this.hello = function(){
   alert(`Hello,${this.name}`);
 }
 }

这个函数包含一个属性name和一个方法hello。
在JavaScript中,可以通过new关键字来调用Student函数(不写new就是一个普通函数,写new就是一个构造函数),并且返回一个原型指向Student.prototype的对象,如下所示:

var xiaoming = new Student("xiaoming");
alert(xiaoming.name); // xiaoming
xiaoming.hello(); // Hello,xiaoming

如果我们想确认一下我们的设想对不对,就会希望去比较一下xiaoming.prototype和Student.prototype是否相等。
但是xiaoming没有prototype属性,不过可以用__proto__来查看。接下来我们就用这些属性来查看xiaoming,Student,Object之间的原型链:

document.onreadystatechange = function(){
 // interactive表示文档已被解析,但浏览器还在加载其中链接的资源
 if(document.readyState === "interactive"){
  var xiaoming = new Student("xiaoming");
  alert(xiaoming.name);
  xiaoming.hello();
  console.log("xiaoming.__proto__:");
  console.log(xiaoming.__proto__);
  console.log("Student.prototype:");
  console.log(Student.prototype);
  console.log("xiaoming.__proto__ === Student.prototype:" + xiaoming.__proto__ === Student.prototype);
  console.log("Student.prototype.constructor:" + Student.prototype.constructor);
  console.log("Student.prototype.prototype:" + Student.prototype.prototype);
  console.log("Student.prototype.__proto__:");
  console.log(Student.prototype.__proto__);
  console.log(Object.prototype);
  console.log("Student.prototype.__proto__ === Object.prototype:" + Student.prototype.__proto__ === Object.prototype);
 }
}


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。