Javascript:理解原型链 [英] Javascript: Understanding Prototype chain
问题描述
我创建了一个简单的类,如下所示:
var Class = function() {};Class.prototype.testObj = {a:2, b:3};
现在如果我执行 console.log(Class.testObj)
我得到 undefined
.但是,如果我按如下方式创建该类的实例:
var instance = new Class();控制台日志(instance.testObj)
我得到了预期的输出.
在我的理解中,所有变量都被视为对象并具有原型属性.当在对象中找不到某个键时,将遍历原型链以查找键值对.但是在Class的情况下,它不会遍历原型链.
我错过了什么?new
关键字还做了哪些额外的事情才能使属性可访问?
您必须清楚
立>Class()
是您的构造函数
,而不是实例对象
.所以Class.testObject
将返回undefined
因为Class
没有那个property
.您可以将
prototype
视为对象的配方.几乎每个函数都有一个prototype
属性,它在创建新实例期间使用,并且prototype
在所有对象实例之间共享>构造函数只是一个与
new
一起使用以创建对象的函数当你这样做时
var instance = new Class();
这意味着你正在创建一个Class
的实例对象,因此instance
将继承Class
的prototype
属性.测试:
console.log(instance instanceof Class);//=>真的console.log(instance.constructor === Class);//=>真的console.log(Object.prototype.isPrototypeOf(Class));//=>真的console.log(Class.prototype.isPrototypeOf(instance));//=>真的
I created a simple class as follows:
var Class = function() {};
Class.prototype.testObj = {a:2, b:3};
Now if I do console.log(Class.testObj)
I get undefined
. But if i create instance of that Class as follows:
var instance = new Class();
console.log(instance.testObj)
I get expected output.
In my understanding, all variables are treated as Objects and have prototype property. When some key is not found in the object, prototype chain is traversed to look for the key-value pair. But in case of Class, it is not traversing the prototype chain.
What am I missing? What additional does new
keyword do such that property is accessible?
You must be clear that
Class()
is yourconstructor
, not aninstance object
. soClass.testObject
will returnundefined
becauseClass
doesn't have thatproperty
.You can think of a
prototype
as a recipe for an object. Almost every function has aprototype
property that is used during the creation of new instances and thatprototype
is shared among all of the object instancesA constructor is simply a function that is used with
new
to create an objectWhen you do this
var instance = new Class();
It means you are creating an instance object ofClass
, henceinstance
will inheritprototype
properties ofClass
.Test:
console.log(instance instanceof Class); // => true console.log(instance.constructor === Class); // => true console.log(Object.prototype.isPrototypeOf(Class)); // => true console.log(Class.prototype.isPrototypeOf(instance)); // => true
这篇关于Javascript:理解原型链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!