使用javascript

时间:2016-02-23 15:12:19

标签: javascript inheritance

我在Javascript中尝试使用Object.create()继承方式。

虽然我清楚地知道这是使用Object.create()实现继承的方式。

//Inheritance with Object.create()

function superClass(){
    this.name = "I'm a name in superclass";
  this.name2 = "Someone please pickup the phone.";
}

superClass.prototype.useMe = function(){
    this.name3 = "I'm name3";
  this.name4 = "I'm name4";
}

function subClass() {
    superClass.call(this);
}
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
var obj = new subClass();

console.log(obj.constructor);

Output:
function subClass() {
    superClass.call(this);
}

当我移动这两行的位置时出现了混乱,

subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;

见下文,

//Inheritance with Object.create()

function superClass(){
    this.name = "I'm a name in superclass";
  this.name2 = "Someone please pickup the phone.";
}

superClass.prototype.useMe = function(){
    this.name3 = "I'm name3";
  this.name4 = "I'm name4";
}

function subClass() {
    superClass.call(this);
}

var obj = new subClass();
subClass.prototype = Object.create(superClass.prototype);
//I've commented the constructor assignment. 
//subClass.prototype.constructor = subClass;

console.log(obj.constructor);

Output:
function subClass() {
    superClass.call(this);
}

我不想将构造函数作为superClass返回,因为我注释了构造函数赋值行。

现在,问题是; subClass.prototype = Object.create(superClass.prototype);的定位是否真的很重要?

案例1:当我将它放在对象创建行上方时,需要分配新的构造函数。

案例2:当我将它放在对象创建行下面时,我认为我们不需要构造函数赋值行,因为它清楚地引用了正确的构造函数。

感谢您的帮助。

编辑:我没有将Object.create与构造函数混合使用。 我唯一的困惑是;当我在创建对象后放置行subClass.prototype = Object.create(superClass);时,它应该将subClass.prototype.constructor更改为superClass的构造函数。但它并没有采用subClass的构造函数。怎么样?或者,我在这里遗漏了一些东西。

0 个答案:

没有答案