JavaScript原型继承和“new”关键字
javascript prototypal inheritance and the 'new' keyword
我一直在 JavaScript 中玩原型继承,并对 new
关键字的行为感到困惑。我不明白为什么继承对象的[[prototype]]
属性指向Function.prototype
而不是继承对象的原型。考虑 2 个构造函数(如下(:
function Animal(name) {
this.name = name;
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = new Animal();
查询构造函数的原型Cat
,我得到了一些有趣的结果:
Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
Cat.__proto__ === Function.prototype; //returns true
Cat.prototype instanceof Animal; //returns true, as expected
我的理解是,当我们将其原型属性设置为新的Animal
实例时,应该更新Cat
的[[prototype]]
以指向Animal.prototype
,这本质上应该
- 基于
Animal.prototype
创建新对象 和 - 内部设置
Cat.[[prototype]]
Animal
的外部原型属性?
我已经在Chrome和FF中尝试过这个,结果相同。什么给?
另外,当我们将Cat.prototype
分配给new Animal()
时,Cat.prototype
应该是什么?即:
//if Cat.prototype = new Animal();
//then
Cat.prototype === Animal.prototype; //get false. Should this be true?
Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
Cat.__proto__ === Function.prototype; //returns true
构造函数Cat
是一个函数。因此,它继承自Function.prototype
而又继承自Object.prototype
.对于Animal
构造函数和所有其他函数对象也是如此。
仅仅因为您分配给Cat.prototype
不会更改Cat
构造函数本身的继承链接(继承链接无论如何都是不可变的(。
请注意,Cat
实例不是从 Cat
继承,而是从 Cat.prototype
继承。因此,无论如何,您都不关心Cat
构造函数的原型链接。
[[prototype]] 属性由 Object 而不是构造函数拥有。所以在你的例子中,你会发现
Cat.prototype.__proto__ === Animal.prototype; //Return true
常说
Instance.__proto__ === Constructor.prototype; //Retrun true
Cat 是一个构造函数,它是函数类型的实例,所以你看到了这个结果
Cat.__proto__ === Function.prototype; //Return true
我的英语太糟糕了,但我希望我已经解释了一些事情。
相关文章:
- 如何在不使用 new 关键字的情况下从函数创建对象
- “new”关键字是在构造对象时自动设置“constructor”属性的唯一方法吗
- 使用“new”关键字创建的对象和使用“Object.create”创建的对象给出不同的结果
- JavaScript:古代代码使用“new”关键字启动简单对象.为什么
- 将 JavaScript new 关键字与可变长度参数数组一起使用
- 如何判断对象是使用“Object.create”还是使用文字语法/“new”关键字创建的
- 在 anthor object 中使用 Object 方法,而无需在 javascript 中使用 new 关键字
- 使用“new”关键字的Javascript函数表达式视为“静态”是否正确?
- 在javascript中使用“new”关键字的替代方案是什么?
- JavaScript 'new' 关键字,带或不带 '()'
- Javascript Module Pattern 和 new 关键字
- Javascript中“new”关键字的限制
- javascript初始化一个没有new关键字的对象
- 闭包可以使用new关键字和区别,例如,在创建新对象/类时
- 函数中的Javascript“new”关键字
- JavaScript原型继承和“new”关键字
- 在Javascript中使用instanceof自定义对象而不使用new关键字
- 如何给一个对象's与javascript中的new关键字的属性和方法
- 为什么函数在构造函数中声明时不使用new关键字
- JavaScript避免new关键字