JavaScript中的构造函数和继承 [英] Constructors and inheritance in JavaScript

查看:190
本文介绍了JavaScript中的构造函数和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于JavaScript中的继承。

This is about "inheritance" in JavaScript.

假设我创建一个构造函数Bird(),另一个叫做Parrot(),我将其继承 Bird的属性通过将其实例分配给Parrot的原型,如下面的代码所示:

Suppose I create a constructor Bird(), and another called Parrot() which I make to "inherit" the properties of Bird by assigning an instance of it to Parrot's prototype, like the following code shows:

function Bird() {
    this.fly = function(){};
}

function Parrot() {
    this.talk = function(){ alert("praa!!"); };
}
Parrot.prototype = new Bird();

var p = new Parrot();

p.talk(); // Alerts "praa!!"
alert(p.constructor); // Alerts the Bird function!?!?!

在我创建了一个Parrot实例后,为什么它的.constructor属性为Bird() ,而不是Parrot(),它是我用来创建对象的构造函数?

After I've created an instance of Parrot, why is the .constructor property of it Bird(), and not Parrot(), which is the constructor I've used to create the object?

推荐答案

Prototype是一个对象与JavaScript中的任何其他内容一样,对象分配也可以通过引用。你刚刚给鹦鹉的原型分配了一只新鸟,所以鹦鹉的原型现在是一只鸟的实例。鸟的建造者是伯德。

Prototype is an object just like anything else in JavaScript and object assignments are by reference. You just assigned a new bird to parrot's prototype so parrot's prototype is now a bird instance. And a bird's constructor is Bird.

你可以用行来解决这个问题

You could fix this with the line

Parrot.prototype.constructor = Parrot;

另一种方法是将Bird的原型克隆分配给Parrot.prototype

Another way to do this would be to assign a clone of Bird's prototype to Parrot.prototype

function deepClone(obj) {
    var clone = {};
    for(var i in obj) {
        if(typeof(obj[i])==="object") {
            clone[i] = deepClone(obj[i]);
        } else {
            clone[i] = obj[i];
        }
    }
    return clone;
}


Parrot.prototype = deepClone(Bird.prototype);
Parrot.prototype.constructor = Parrot;

我更喜欢这个因为:

1 )它可以节省创建一个任意鸟类实例(如果有多少鸟已经计算出来的话会怎样)

1) it saves creating an arbitrary instance of bird (what if something is counting hwo many birds have been created)

2)如果Bird构造函数接受了一个被测试的参数怎么办?构造函数体?然后
调用:

2) What if Bird constructor took an argument which was tested in the constructor body? Then calling:

Parrot.prototype = new Bird();

然后可能会导致空指针

这篇关于JavaScript中的构造函数和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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