Home  >  Article  >  Web Front-end  >  What is the JavaScript prototype chain?

What is the JavaScript prototype chain?

零下一度
零下一度Original
2017-07-21 17:33:431515browse

## This article mainly introduces the detailed explanation of prototypes and prototype chains in JavaScript. This article explains private variables and functions, static variables and functions, instance variables and functions, prototypes and prototypes For the basic concept of chain, friends who need it can refer to

Every object in JavaScript has a built-in attribute prototype. The explanation of the prototype attribute of an object in Javascript is: return a reference to the prototype of the object type. What this means is that the prototype attribute holds a reference to another JavaScript object that serves as the parent object of the current object.

1. JavaScript classes and objects

Many books will talk about how to define "classes" in JS. Generally speaking, you use the following code :

1 function foo () {2     this.x = 1;3     this.y = 2;4 }5 var obj = new foo();  //{x:1, y:2}
 

In fact, this is a very bad language mechanism. We must first make it clear that there is no such thing as a "class" in JS. Before understanding it, we need to first understand the development history of JS.

JavaScript was born with the Internet and browsers. In the early years, the Internet was still relatively poor, the cost of Internet access was relatively high, the Internet speed was very slow, and it usually took a long time. It takes time to transfer a plain text HTML file. So at that time, Netscape proposed that there needed to be a solution that could enable some operations to be performed on the client without going through the server. For example, if a user misses an "@" when filling in their email address, it can be checked on the client. Errors and prompts to the user without parsing on the server, which can greatly reduce the delay and bandwidth consumption caused by communication operations. At that time, JAVA happened to come out, and it was very popular, so Netscape decided to cooperate with SUN to embed JAVA applets (later called Java applets) into the browser. However, controversy arose later about this solution, because the browser originally only required a small operation, and the JAVA language itself was too "heavy", and it was overkill to deal with form validation issues, so we decided to develop a new one. Language to support lightweight operations on the client side, and learn from the syntax of JAVA. So Netscape developed a new lightweight language, which is biased towards C and JAVA in terms of syntax, and JAVA in terms of data structure. This language was originally called Mocha, and after years of evolution, it became the current JavaScript.

The story ends here, and it seems to have nothing to do with this article... Don't worry, we will get to the point soon. Why is this language named JavaScript? In fact, it has nothing to do with JAVA. It is just because at that time, the object-oriented method had just come out, and all programmers respected learning the object-oriented method. In addition, JAVA With its sudden emergence and vigorous promotion, anything related to JAVA is like putting gold on its face, bringing with it its own halo. So I used the reputation of JAVA to promote it, but just lip service is not enough. Because of the admiration of object-oriented methods, everyone is accustomed to object-oriented syntax, which is written in the method of new Class() code. However, the JavaScript language itself does not have the concept of a class. It is a hodgepodge of multiple languages. In order to be more suitable for programmers who are accustomed to object-oriented syntax, the new operator was born.

Okay, after telling so many stories, I just want to tell the students that the new operator itself is a thing full of ambiguity in JavaScript. There is no concept of class, it just fits the programmer's habits. So what is the relationship between the new operator and objects in JavaScript? Consider the following code:

1 function foo () {2     this.x = 1;3     this.y = 2;4     return {5         z:36     }7 }8 var obj = new foo();  //{z:3}

  咦?发生了什么奇怪的事情,x 和 y 哪里去了?实际上 new 操作符并不是传统面向对象语言那样,创建一个类的实例,new 操作符实际上只是在引擎内部帮我们在函数的开始创建好了一个对象,然后将函数的上下文绑定到这个对象上面,并在函数的末尾返回这个对象。这里需要注意的问题是,如果我们手动的返回了一个对象,那么按照函数执行机制,一旦返回了一个值,那么该函数也就执行结束,后面的代码将不会执行,所以说在刚才的例子中我们得到的对象只是我们手动定义的对象,并不是引擎帮我们创建的对象。 new 操作符实际上类似于以下操作:

1 function foo () {2     //新创建一个对象,将 this 绑定到该对象上3     4     //在这里编写我们想要的代码5 6     //return this;7 }

  不过需要注意的是,new 操作符只接受 Object 类型的值,如果我们手动返回的是基本类型,则还是会返回 this :

1 function foo () {2     this.x = 1;3     this.y = 2;4     return 0;5 }6 var obj = new foo();  //{x:1, y:2}

  现在我们现在可以将 new 操作符定义成以下方法:

 1 function newOpertor (cls, ...args) { 2     var obj = {}; 3     cls.apply(obj, args); 4     return obj; 5 } 6  7 function foo (x, y) { 8     this.x = x; 9     this.y = y;10 }11 12 var obj = newOpertor(foo, 1, 2);  //{x:1, y:2}

 二、对象的原型

   JavaScript 中存在类似继承的机制,但是又不是标准面向对象的继承,在 JS 中使用的是原型的机制。要记住,在 JS 中只有对象,没有类,对象的继承是由原型来实现,笼统的来说可以这样理解,一个对象是另一个对象的原型,那么便可以把它比作父类,子类既然也就继承了父类的属性和方法。

1 function foo () {2     this.x = 1;3     this.y = 2;4 }5 6 foo.prototype.z = 37 8 var obj = new foo();9 console.log(obj.z);  //3

  [[prototype]] 是函数的一个属性,这个属性的值是一个对象,该对象是所有以该函数为构造器创造的对象的原型。可以把它近似的理解为父类对象,那么相应的,子类自然会继承父类的属性和方法。不过为什么要区分原型继承和类继承的概念呢?标准的面向对象方法,类是不具有实际内存空间,只是一个事物的抽象,对象才是事物的实体,而通过继承得到的属性和方法,同属于该对象,不同的对象各自都拥有独立的继承而来的属性。不过在 JavaScript 当中,由于没有类的概念,一直都是对象,所以我们“继承”的,是一个具有实际内存空间的对象,也是实体,也就是说,所有新创建的子对象,他们共享一个父对象(后面我统称为原型),不会拥有独立的属性:

 1 function foo () { 2     this.x = 1; 3     this.y = 2; 4 } 5  6 foo.prototype.z = 3 7  8 var obj1 = new foo(); 9 10 console.log(obj1.z);  //311 12 foo.prototype.z = 213 14 console.log(obj1.z);  //2

  还记得我们之前所说的 new 操作符的原理吗?new 操作符的本质不是实例化一个类,而是引擎贴合习惯了面向对象编程方法的程序员,所以说 [[prototype]] 属性本质上也是 new 操作符的一个副产物。这个属性只在函数上面有意义,该属性定义了 new 操作符产生的对象的原型。除了 [[prototype]] 可以访问到对象原型以外,还有一个非标准的方法,在每一个对象中都有一个 __proto__ 属性,这个属性直接关联到了该对象的原型。这种方法没有写入 W3C 的标准规范,但是却得到了浏览器的广泛支持,许多浏览器都提供了该方法以供访问对象的原型。(个人觉得 __proto__ 比 [[prototype]] 更能体现原型链的本质)

 1 function foo () { 2     this.x = 1; 3     this.y = 2; 4 } 5  6 foo.prototype.z = 3 7  8 var obj1 = new foo(); 9 10 console.log(obj1.__proto__);  //{z:3}

  除了使用 new 操作符和函数的 [[prototype]] 属性定义对象的原型之外,我们还可以直接在对象上显示的通过 __proto_ 来定义,这种定义对象原型的方式更能够体现出 JavaScript 语言的本质,更能够使初学者理解原型链继承的机制。

1 var father = {x:1};2 3 var child = {4     y:2,5     __proto__:father6 };7 8 console.log(child.x);  //1

  现在我们来完成之前那个自定义 new 操作(如果你还不能理解这个函数,没有关系,跳过它,这并不影响你接下来的学习):

 1 function newOpertor (cls, ...args) { 2     var obj = Object.create(cls.prototype); 3     cls.apply(obj, args); 4     return obj; 5 } 6  7 function foo (x, y) { 8     this.x = x; 9     this.y = y;10 }11 12 foo.prototype.z = 313 14 var obj1 = newOpertor(foo, 1, 2)15 16 console.log(obj1.z);  //3

 三、原型链

  介绍完原型之后,同学们需要明确以下几个概念:

  •   JavaScript 采用原型的机制实现继承;

  •   原型是一个具有实际空间的对象,所有关联的子对象共享一个原型;

  那么 JavaScript 当中的原型是如何实现相互关联的呢?JS 引擎又是如何查找这些关联的属性呢?如何实现多个对象的关联形成一条原型链呢?

 1 var obj1 = { 2     x:1 3 } 4  5 var obj2 = { 6     y:2, 7     __proto__:obj1 8 } 9 10 var obj3 = {11     z:3,12     __proto__:obj213 }14 15 console.log(obj3.y);  //216 console.log(obj3.x);  //1

  在上面这段代码,我们可以看出,对象的原型可以实现多层级的关联的操作,obj1 是 obj2 的原型, obj2 同时又是 obj3 的原型,这种多层级的原型关联,就是我们常说的原型链。在访问一个处于原型链当中的对象的属性,会沿着原型链对象一直向上查找,我们可以把这种原型遍历操作看成是一个单向的链表,每一个处于原型链的对象都是链表当中的一个节点,JS 引擎会沿着这条链表一层一层的向下查找属性,如果找到了一个与之匹配的属性名,则返回该属性的值,如果在原型链的末端(也就是 Object.prototype)都没有找到与之匹配的属性,则返回 undefined。要注意这种查找方式只会返回第一个与之匹配的属性,所以会发生属性屏蔽:

 1 var obj1 = { 2     x:1 3 } 4  5 var obj2 = { 6     x:2, 7     __proto__:obj1 8 } 9 10 var obj3 = {11     x:3,12     __proto__:obj213 }14 15 console.log(obj3.x);  //3

  若要访问原型的属性,则需要一层的一层的先向上访问原型对象:

1 console.log(obj3.__proto__.x);  //22 console.log(obj3.__proto__.__proto__.x);  //1

  要注意的一点是,原型链的遍历只会发生在 [[getter]] 操作上,也就是取值操作,也可以称之右查找(RHS)。相反,若是进行 [[setter]] 操作,也就是赋值操作,也可以称作左查找(LHS),则不会遍历原型链,这条原则保证了我们在对对象进行操作的时候不会影响到原型链:

 1 var obj1 = { 2     x:1 3 } 4  5 var obj2 = { 6     __proto__:obj1 7 } 8  9 console.log(obj2.x);  //110 11 obj2.x = 2;12 13 console.log(obj2.x);  //214 console.log(obj1.x);  //1(并没有发生变化)

   在遍历原型链中,如果访问带有 this 引用的方法,可能会发生令你意想不到的结果:

 1 var obj1 = { 2     x:1, 3     foo: function  () { 4         console.log(this.x); 5     } 6 } 7  8 var obj2 = { 9     x:2,10     __proto__:obj111 }12 13 obj2.foo();  //2

  在上面的内容中,我们讨论过,对象的原型相当于父类,我们可以继承它所拥有的属性和方法,所以在我们访问 foo() 函数的时候时候,实际上调用该方法的对象是 obj2 而不是 obj1。关于更详细的内容,需要了解 this 和上下文绑定,这不在本篇文章的讨论范围之内。

  关于原型链的问题,大家需要理解的一点是,任何对象的原型链终点,都是 Object.prototype,可以把 Object 理解为所有对象的父类,类似于 JAVA 一样,所以说所有对象都可以调用一些 Object.prototype 上面的方法,比如 Object.prototype.valueOf() 以及 Object.prototype.toString() 等等。所有的 string 类型,其原型为 String.prototype ,String.prototype 是一个对象,所以其原型也就是 Object.prototype。这就是我们为什么能够在一个 string 类型的值上调用一些方法,比如 String.prototype.concat() 等等。同理所有数组类型的值其原型是 Array.prototype,数字类型的值其原型是 Number.prototype:

1 console.log({}.__proto__ === Object.prototype);  //true2 3 console.log("hello".__proto__ === String.prototype);  //true4 5 console.log(1..__proto__ === Number.prototype);  //true6 //注意用字面量访问数字类型方法时,第一个点默认是小数标志7 8 console.log([].__proto__ === Array.prototype);  //true

   理解了原型链的遍历操作,我们现在就可以学习如何添加属于自己的方法。我们现在知道了所有字符串的原型都是 String.prototype ,那么我们可以对其进行修改来设置我们自己的内置方法:

1 String.prototype.foo = function () {2     return this + " foo";3 }4 5 console.log("bar".foo());  //bar foo

  所以说,在处理一些浏览器兼容性问题的时候,我们可以直接修改内置对象来兼容一些旧浏览器不支持的方法,比如 String.prototype.trim() :

1 if (!String.prototype.trim) {2     String.prototype.trim = function() {3         return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');4     };5 }

  不过需要注意,切忌随意修改内置对象的原型方法,一是因为这会带来额外的内存消耗,二是这可能会在系统中造成一些隐患,一般只是用来做浏览器兼容的 polyfill 。

四、 有关原型的方法

   for ... in 语句会遍历原型链上所有可枚举的属性(关于属性的可枚举性质,可以参考 《JavaScript 常量定义》),有时我们在操作的时候需要忽略掉原型链上的属性,只访问该对象上的属性,这时候我们可以使用 Object.prototype.hasOwnProperty() 方法来判断属性是否属于原型属性:

 1 var obj1 = { 2     x:1, 3 } 4  5 var obj2 = { 6     y:2, 7     __proto__:obj1 8 } 9 10 for(var key in obj2){11     console.log(obj2[key]);  //2, 112 }13 14 for(var key in obj2){15     if(obj2.hasOwnProperty(key)){16         console.log(obj2[key]);  //217     }18 }

  我们知道通过 new 操作符创建的对象可以通过 instanceof 关键字来查看对象的“类”:

1 function foo () {}2 3 var obj = new foo();4 5 console.log(obj instanceof foo);  //true

  实际上这个操作也是不严谨的,我们现在已经知道了 new 操作符在 JavaScript 当中本是一个具有歧义设计,instanceof 操作符本身也是一个会让人误解的操作符,它并没有实例这种说法,实际上这个操作符只是判断了对象与函数原型的关联性,也就是说其返回的是表达式 object.__proto__ === function.prototype 的值。

 1 function foo () {} 2  3 var bar = { 4     x:1 5 } 6  7 foo.prototype = bar 8  9 var obj = {10     __proto__: bar11 }12 13 console.log(obj instanceof foo);  //true

  在这一段代码中,我们可以看出 obj 和 foo 并没有任何关系,只是 obj 的原型和 foo.prototype 关联到了同一个对象上面,所以其结果会返回 true。  

  不过对基本类型类型使用 instanceof 方法的话,可能会产生意外的结果:

1 console.log("1" instanceof String);  //false2 3 console.log(1 instanceof Number);  //false4 5 console.log(true instanceof Boolean);  //false

  但是我们同样可以使用使用字面量调用原型的方法,这可能会让人感到困惑,不过我们不用担心它,并不是原型链出现什么毛病,而是在对基本类型进行字面量操作的时候,会涉及到隐式转换的问题。JS 引擎会先将字面量转换成内置对象,然后在调用上面的方法,隐式转换问题不在本文的讨论范围之类,大家可以参考 Kyle Simpson — 《你不知道的 JavaScript (中卷)》。

  实际对象的 Object.prototype.isPrototypeOf() 方法更能体现出对象原型链的关系,此方法判断一个对象是否是另一个对象的原型,不同于 instanceof 的是,此方法会遍历原型链上所有的节点,若有匹配项则返回 true:

 1 var obj1 = { 2 } 3  4 var obj2 = { 5     __proto__:obj1 6 } 7  8 var obj3 = { 9     __proto__:obj210 }11 12 console.log(obj2.isPrototypeOf(obj3));  //true13 console.log(obj1.isPrototypeOf(obj3));  //true14 console.log(Object.prototype.isPrototypeOf(obj3));  //true

  在 ES5 当中拥有标准方法 Object.getPrototypeOf() 可以供我们获得一个对象的原型,在ES6 当中拥有新的方法 Object.setPrototypeOf() 可以设置一个对象的原型,不过在使用之前请先查看浏览器兼容性。

 1 var obj1 = { 2     x:1 3 } 4  5 var obj2 = { 6     y:2 7 } 8  9 Object.setPrototypeOf(obj2, obj1);10 11 console.log(Object.getPrototypeOf(obj2) === obj1);  //true

  我们现在知道,通过 new 操作符创建的对象,其原型会关联到函数的 [[prototype]] 上面,实际上这是一个很糟糕的写法,一味的贴合面向对象风格的编程模式,使得很多人无法领域 JavaScript 当中的精髓。许多书籍都会写到 JavaScript 中有许多奇怪的地方,然后教你如何避开这些地雷,实际上这不是一个好的做法,并不是因为 JavaScript 是一门稀奇古怪的语言,而是我们不愿意去面对它的特性,正确的理解这些特性,才能让我们写出更加高效的程序。Object.create() 方法对于对象之间的关联和原型链的机制更加清晰,比 new 操作符更加能够理解 JavaScript 的继承机制。该方法创建一个新对象,并使新对象的原型关联到参数对象当中:

1 var obj1 = {2     x:13 }4 5 var obj2 = Object.create(obj1);6 7 console.log(obj1.isPrototypeOf(obj2));  //true

  不过使用的时候还需要注意浏览器的兼容性,下面给出 MDN 上面的 polyfill:

 1 (function() { 2     if (typeof Object.create != 'function') { 3         Object.create = (function() { 4             function Temp() {} 5             var hasOwn = Object.prototype.hasOwnProperty; 6             return function(O) { 7                 if (typeof O != 'object') { 8                     throw TypeError('Object prototype may only be an Object or null'); 9                 }10                 Temp.prototype = O;11                 var obj = new Temp();12                 Temp.prototype = null;13                 if (arguments.length > 1) {14                     var Properties = Object(arguments[1]);15                     for (var prop in Properties) {16                         if (hasOwn.call(Properties, prop)) {17                             obj[prop] = Properties[prop];18                         }19                     }20                 }21                 return obj;22             };23         })();24     }25 })();

  关于 Object.create() 方法要注意的一点是,如果参数为 null 那么会创建一个空链接的对象,由于这个对象没有任何原型链,所以说它不具有任何原生的方法,也无法进行原型的判断操作,这种特殊的对象常被称作“字典”,它完全不会受原型链的干扰,所以说适合用来存储数据:

 1 var obj = Object.create(null); 2 obj.x = 1 3  4 var bar = Object.create(obj); 5 bar.y = 2; 6  7 console.log(Object.getPrototypeOf(obj));  //null 8  9 console.log(Object.prototype.isPrototypeOf(obj));  //false10 11 console.log(obj instanceof Object);  //false12 13 console.log(bar.x);  //114 15 obj.isPrototypeOf(bar);  //TypeError: obj.isPrototypeOf is not a function16 17 /**18  * 注意由于对象没有关联到 Object.prototype 上面,所以无法调用原生方法,但这并不影响此对象的关联操作。19  */

 总结

  原型链是 JavaScript 当中非常重要的一点,同时也是比较难理解的一点,因为其与传统的面向对象语言有着非常大的区别,但这是正是 JavaScript 这门语言的精髓所在,关于原型与原型链,我们需要知道以下这几点:

  •   JavaScript 通过原型来实现继承操作;

  •   几乎所有对象都有原型链,其末端是 Object.prototype;

  •   原型链上的 [[getter]] 操作会遍历整条原型链,[[setter]] 操作只会针对于当前对象;

  •   我们可以通过修改原型链上的方法来添加我们想要的操作(最好不要这样做);

  关于 JavaScript 原型链,在一开始人们都称为“继承”,其实这是一种不严谨的说法,因为这不是标准的面向对象方法,不过初期人人常常这么理解。现在我往往称之为关联委托,关联指的是一个对象关联到另一个对象上,而委托则指的是一个对象可以调用另一个对象的方法。

The above is the detailed content of What is the JavaScript prototype chain?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn