Javascript:理解原型链 [英] Javascript: Understanding Prototype chain

查看:47
本文介绍了Javascript:理解原型链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的类,如下所示:

var Class = function() {};Class.prototype.testObj = {a:2, b:3};

现在如果我执行 console.log(Class.testObj) 我得到 undefined.但是,如果我按如下方式创建该类的实例:

var instance = new Class();控制台日志(instance.testObj)

我得到了预期的输出.

在我的理解中,所有变量都被视为对象并具有原型属性.当在对象中找不到某个键时,将遍历原型链以查找键值对.但是在Class的情况下,它不会遍历原型链.

我错过了什么?new 关键字还做了哪些额外的事情才能使属性可访问?

解决方案

  1. 您必须清楚Class() 是您的构造函数,而不是实例对象.所以 Class.testObject 将返回 undefined 因为 Class 没有那个 property.

  2. 您可以将 prototype 视为对象的配方.几乎每个函数都有一个 prototype 属性,它在创建新实例期间使用,并且 prototype 在所有对象实例之间共享

  3. 构造函数只是一个与new一起使用以创建对象的函数

  4. 当你这样做时var instance = new Class();这意味着你正在创建一个Class的实例对象,因此instance 将继承 Classprototype 属性.

  5. 测试:

    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?

解决方案

  1. You must be clear that Class() is your constructor, not an instance object. so Class.testObject will return undefined because Class doesn't have that property.

  2. You can think of a prototype as a recipe for an object. Almost every function has a prototype property that is used during the creation of new instances and that prototype is shared among all of the object instances

  3. A constructor is simply a function that is used with new to create an object

  4. When you do this var instance = new Class(); It means you are creating an instance object of Class, hence instance will inherit prototype properties of Class.

  5. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆