You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
vararr=[1,2,3];console.log(arr.constructor);//输出 function Array(){}vara={};console.log(arr.constructor);//输出 function Object(){}varbool=false;console.log(bool.constructor);//输出 function Boolean(){}varname="hello";console.log(name.constructor);//输出 function String(){}varsayName=function(){}console.log(sayName.constrctor)// 输出 function Function(){}//接下来通过构造函数创建instancefunctionA(){}vara=newA();console.log(a.constructor);//输出 function A(){}
functionPerson(name){this.name=name;}Person.prototype.sayName=function(){console.log(this.name);}varperson=newPerson("xl");console.log(person.constructor);//输出 function Person(){}console.log(Person.prototype.constructor);//输出 function Person(){}console.log(Person.constructor);//输出 function Function(){}
本文为了解决以下问题:
__proto__
(实际原型)和prototype
(原型属性)不一样!!!constructor
属性(原型对象中包含这个属性,实例当中也同样会继承这个属性)prototype
属性(constructor.prototype
原型对象)__proto__
属性(实例指向原型对象的指针)首先弄清楚几个概念:
##什么是对象
若干属性的集合
##什么是原型?
原型是一个对象,其他对象可以通过它实现继承。
##哪些对象有原型?
所有的对象在默认情况下都有一个原型,因为原型本身也是对象,所以每个原型自身又有一个原型(只有一种例外,默认的对象原型在原型链的顶端)
##任何一个对象都可以成为原型
接下来就是最核心的内容:
constructor 属性
以上部分即解释了任何一个对象都有constructor属性,指向创建这个对象的构造函数
##prototype属性
注意:prototype是每个
函数对象
都具有的属性,被称为原型对象,而__proto__
属性才是每个对象才有的属性。一旦原型对象被赋予属性和方法,那么由相应的构造函数创建的实例会继承prototype
上的属性和方法##constructor属性和prototype属性
每个函数都有
prototype
属性,而这个prototype
的constructor
属性会指向这个函数。如果我们重写(重新定义)这个
Person.prototype
属性,那么constructor
属性的指向就会发生改变了。接下来解释为什么,看下面的例子
接下解释
__proto__
和prototype
属性同样拿上面的代码来解释:
首先给构造函数的原型对象
Person.prototype
赋给sayName
方法,由构造函数Person
创建的实例person
会继承原型对象上的sayName
方法。###为什么会继承原型对象的方法?
因为ECMAscript的发明者为了简化这门语言,同时又保持继承性,采用了链式继承的方法。
由
constructor
创建的每个instance
都有个__proto__
属性,它指向constructor.prototype
。那么constrcutor.prototype
上定义的属性和方法都会被instance
所继承.参考文章:
The text was updated successfully, but these errors were encountered: