【发布时间】:2017-09-28 07:48:43
【问题描述】:
我需要一些关于对象实例化和继承的说明。考虑以下代码和后续观察:
function TestObject() {
this.TestProperty1 = "TestProperty1";
this.TestFunction1 = function() {
console.log(this.TestProperty1);
}
}
TestObject.prototype.TestProperty2 = "TestProperty2";
TestObject.prototype.TestFunction2 = function() {
console.log(this.TestProperty2);
}
new关键字
let TestInstance1 = new TestObject();
console.log(TestInstance1);
根据我的 OOP 经验,输出正是我所期望的。 TestInstance1 属于 TestObject 类型,它可以访问其成员和原型成员。
new Object()
let TestInstance2 = new Object(TestObject.prototype);
console.log(TestInstance2);
输出表明TestInstance2 属于Object 类型而不是TestObject,但是它获得了引用TestObject 的constructor 属性。它只能访问TestObject的原型成员。
Object.create()
let TestInstance3 = Object.create(TestObject.prototype);
console.log(TestInstance3);
输出表明TestInstance3 属于TestObject 类型,但它只能访问其原型成员。
问题
为什么要使用new Object() 方法而不是new 关键字方法?返回一个 Object 实例并引用传递给其构造函数的类型而不是简单地返回该类型本身的实例似乎很奇怪。
在标准的第一版中是否提供 new 关键字方法,就像 new Object() 方法一样?我觉得它是后来添加的,因为我看不出有任何理由使用 new Object() 方法而不是 new 关键字方法。
由于Object.create() 是最近才添加到该语言中的,它打算解决什么问题?
【问题讨论】:
标签: javascript object inheritance prototype prototypal-inheritance