今天重温了下Javacript,给你们带来一篇Javascript博文,相信对于Javacript有必定了解的人都听过prototype原型这个概念,今天咱们深度的分析下prototype与__proto__。javascript
好了,下面看一个很是简单的例子:java
var Person = function(name) { this.name = name ; }; var p = new Person("Ben"); console.log(p.name);代码简单的 你不用说明了,若是如今让你们根据上面的代码画一张包含Function与Object的内存图,你们确定回想什么叫包含Function与Object,上面的代码和它们有几毛钱的关系。好了,下面我先按要求把图画出来,你们参考下:
解析下:函数
一、任何一个由构造器产生的对象都有__proto__属性,且此属性指向该构造器的prototype。this
二、全部构造器/函数的__proto__都指向Function的prototypespa
拿第2条对比第1条,貌似咱们发现了什么,没错函数的构造器就是Function,看下面的代码:prototype
//函数表达式 var Person = function(name) { this.name = name ; }; //函数声明 function Person(name) { this.name = name ; } //上面两种方式实际上就至关与new Function var Person = new Function("name" , "this.name = name ;" );固然了不能说说,下面看代码验证:
console.log(Person.__proto__ === Function.prototype); //true console.log(typeof p.__proto__);//objcect console.log(p.__proto__.__proto__ === Object.prototype); //true
console.log(Object.__proto__ === Function.prototype); // true console.log(Function.__proto__ === Function.prototype); //true console.log(Function.prototype.__proto__ == Object.prototype); //true console.log(Object.prototype.__proto__); //null
有此可见code
一、全部的构造器包括Object和Function都继承了Function.prototype的方法,由第三行可知全部的构造器都是对象,即js中一切皆为对象。对象
二、__proto__最终的指向都是Object.prototype,这也就是js中的原型链。blog
最后咱们看一下Object的文档:继承
The following table lists properties of the Object Object.
Property |
Description |
---|---|
Specifies the prototype for an object. |
|
Specifies the function that creates an object. |
|
Returns a reference to the prototype for a class of objects. |
一、constructor属性指向的是建立当前对象的构造函数。
二、每一个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数
看下面的例子:
//函数表达式 var Person = function(name) { this.name = name ; }; var p = new Person("Ben"); console.log(p.constructor === Person);//true console.log(Person.prototype.constructor === Person); //true console.log(Person.prototype instanceof Object); //true console.log(Person.prototype instanceof Person); //false //改变Person的prototype Person.prototype = {name:"123"} ; var p2 = new Person("Ben"); console.log(p2.constructor === Object);//true console.log(p2.constructor === Person.prototype.constructor);//true console.log(Person.prototype.constructor === Object);//true console.log(Person.prototype.constructor === Person);//false
当改变Person的prototype时,会发现,Person.prototype.constructor指向了Object,主要是由于:
Person.prototype = {name:"123"} 至关于Person.prototype=new Object({name:"123"} );此时的构造器变成了Object.
好了,就介绍到这里,各位看官没事留个言,赞一个,哈~。