A thorough understanding of JavaScript in the prototype, __ proto__

Although everything is an object in JavaScript, but in order to understand the prototype chain system, we need to JavaScript objects and functions of the subjects were divided into two categories. Based on this, JavaScript logic prototype chain comply with the following general rules:

  • __Proto__ object has attributes, function has prototype property;
  • Object generated by the function;
  • When generating object, __proto__ property of the object property function prototype points.

In the absence of point __proto__ manually modify the property, more than three points to the prototype chain is the default JavaScript logic.

1, the general situation:

// 创建空对象时,实际上我们是用Object函数来生成对象的:
var o = {}
o.__proto__ === Object.prototype 
// ==> true

// 我们也可以显式的使用Object函数来创建对象:
var o = Object()
o.__proto__ === Object.prototype
// ==> true

// 当我们使用函数来创建自定义的对象时,上面的规则同样适用:
function MyObj(){}
typeof MyObj
// ==> "function"
var mo = new MyObj()
mo.__proto__ === MyObj.prototype
// ==> true     

2, function objects
since one of these JavaScript in "everything is an object", that is a function of the natural object. For functions as an object, the above rules apply:

// 函数对象都是由Function函数生成的:
>function fn(){}
>fn.__proto__ === Function.prototype
// ==> true

// Function函数本身作为对象时,生成它的函数是他自身!
>Function.__proto__ === Function.prototype
// ==> true

// Object函数既然是函数,那生成它的函数自然是Function函数咯:
>Object.__proto__ === Function.prototype
// ==> true

Look at an example:

function Say(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Say('jone', 30);
console.log(person instanceof Say);                                         // ==> true
console.log(person.__proto__ === Say.prototype);                            // ==> true
console.log(person.__proto__.constructor === Say.prototype.constructor);    // ==> true
var obj = {};
console.log(obj.__proto__ == Object.prototype)                              // ==> true
var fn = function() {};
console.log(fn.__proto__ === Function.prototype);                           // ==> true

to sum up:

js li __proto__ All objects have attributes (object function), point to the object constructor function prototype configuration.
Only function that has the function prototype property. This property is a pointer to an object, the object is to use the properties and methods shared by all instances (we called the prototype object to the object). Prototype object also has a property called constructor, this property contains a pointer, it refers back to the original constructor.

Guess you like

Origin www.cnblogs.com/jone-chen/p/11124580.html
Recommended