Inheritance in JavaScript is done through a prototype chain: each object has another object as its prototype, and the object inherits properties from this prototype. For each object, there are three ways to access its prototype object:
1.__proto__. The object's prototype object can be accessed through its __proto__ attribute. This property is supported only in Firefox, Safari, and Chrome, and not in IE and Opera.
2.Object.getPrototypeOf(). You can pass the object as a parameter into the Object.getPrototypeOf() method, and after execution, it returns the object's prototype object. This method is only supported in the ECMAScript 5 standard.
3.o.constructor.prototype. First get the constructor function of the object, and then access the prototype object by accessing the prototype property of the constructor function. The prerequisite for using this method is that there is a constructor attribute pointing to the constructor in the object.
To determine whether there is a prototype chain relationship between two objects, you can use the isPrototype() method:
The code copy is as follows:
var p = {x:1};
var o = Object.create(p);
console.log(p.isPrototypeOf(o));//true
For all objects created with literals, their prototype object is Object.prototype (as a special object, Object.prototype has no prototype object):
The code copy is as follows:
var x = {a:18, b:28};
console.log(x.__proto__);//Object {}
For all objects created with the new operator, their prototype objects are the prototype properties of the constructor function:
The code copy is as follows:
var x = {a:18, b:28};
function Test(c){
this.c = c;
}
Test.prototype = x;
var t = new Test(38);
console.log(t);//Object {c=38, a=18, b=28}
console.log(t.__proto__);//Object {a=18, b=28}
console.log(t.__proto__.__proto__);//Object {}
The process of using the new operator to create an object in JavaScript is as follows:
1. Create a new empty object.
2. Point the __proto__ attribute of this object to the prototype attribute of the constructor function.
3. Use this object as this parameter and execute the constructor function.
From the above creation process, we can draw a conclusion that all objects constructed from the same constructor function have the __proto__ attribute (that is, its prototype object) equal, that is, there is only one prototype object:
The code copy is as follows:
var t = new Test(38);
var t2 = new Test(68);
console.log(t === t2);//false
console.log(t.__proto__ === t2.__proto__);//true