、prototype、constructor

今天重温了下Javacript,给大家带来一篇Javascript博文,相信对于Javacript有一定了解的人都听过prototype原型这个概念,今天我们深度的分析下prototype与__proto__。

好了,下面看一个非常简单的例子:

var Person = function(name){this.name = name ;};var p = new Person("Ben");console.log(p.name);代码简单的 你不用说明了,如果现在让大家根据上面的代码画一张包含Function与Object的内存图,大家肯定回想什么叫包含Function与Object,上面的代码和它们有几毛钱的关系。好了,下面我先按要求把图画出来,大家参考下:

解析下:

1、任何一个由构造器产生的对象都有__proto__属性,且此属性指向该构造器的prototype。

2、所有构造器/函数的__proto__都指向Function的prototype

拿第2条对比第1条,貌似我们发现了什么,没错函数的构造器就是Function,看下面的代码:

//函数表达式var Person = function(name){this.name = name ;};//函数声明function Person(name){this.name = name ;}//上面两种方式实际上就相当与new Functionvar 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有人会问,那么Function与Object的prototype,__prop__到底是什么呢?console.log(Object.__proto__ === Function.prototype); // trueconsole.log(Function.__proto__ === Function.prototype); //trueconsole.log(Function.prototype.__proto__ == Object.prototype); //trueconsole.log(Object.prototype.__proto__); //null

有此可见

1、所有的构造器包括Object和Function都继承了Function.prototype的方法,由第三行可知所有的构造器都是对象,即js中一切皆为对象。

2、__proto__最终的指向都是Object.prototype,这也就是js中的原型链。

最后我们看一下Object的文档:

Properties

The following table lists properties of theObject Object.

Property

Description

__proto__ Property

Specifies the prototype for an object.

constructor Property

Specifies the function that creates an object.

prototype Property

Returns a reference to the prototype for a class of objects.

发现Object还有个constructor属性。

1、constructor属性指向的是创建当前对象的构造函数。

2、每个函数都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数

看下面的例子:

//函数表达式var Person = function(name){this.name = name ;};var p = new Person("Ben");console.log(p.constructor === Person);//trueconsole.log(Person.prototype.constructor === Person); //trueconsole.log(Person.prototype instanceof Object); //trueconsole.log(Person.prototype instanceof Person); //false//改变Person的prototypePerson.prototype = {name:"123"} ;var p2 = new Person("Ben");console.log(p2.constructor === Object);//trueconsole.log(p2.constructor === Person.prototype.constructor);//trueconsole.log(Person.prototype.constructor === Object);//trueconsole.log(Person.prototype.constructor === Person);//false

当改变Person的prototype时,会发现,Person.prototype.constructor指向了Object,主要是因为:

Person.prototype = {name:"123"} 相当于Person.prototype=new Object({name:"123"});此时的构造器变成了Object.

好了,就介绍到这里,各位看官没事留个言,,赞一个,哈~。

因为有梦,所以勇敢出发,选择出发,便只顾风雨兼程。

、prototype、constructor

相关文章:

你感兴趣的文章:

标签云: