在JavaScript中引用子构造函数中的父构造函数属性

Reference Parent Constructor Properties in Child Constructor in JavaScript

本文关键字:构造函数 属性 JavaScript 引用      更新时间:2023-09-26

我有以下

function mild_bird(){
    this.name = "catherine";
    this.origin = "st petersburg";
    this.location = "brighton beach";
}
mild_bird.prototype.get_info = function(){
    return "poo" + ", " + "pee";
}
function wild_bird(nickname){
    this.nickname = nickname;
    //anyway to reference parameters in mild_bird constructor's?
    this.name = mild_bird.prototype.name;
    this.origin = mild_bird.prototype.origin;
    this.location = mild_bird.prototype.location;
}
wild_bird.prototype = new mild_bird();
wild_bird.prototype.constructor = wild_bird;
var the_wild_bird = new wild_bird("sandy");
alert(the_wild_bird.name);

最后一行的警报返回undefined。我希望它返回"凯瑟琳"。是否可以将mild_bird构造函数中的属性传递给wild_bird的构造函数?

您必须在子构造函数中调用父构造函数。使用.call(this)可以确保将上下文设置为由子构造函数创建的对象。

function wild_bird(nickname){
    mild_bird.call(this);
    this.nickname = nickname;
}

回避您的问题:

在JavaScript 中引用子构造函数中的父构造函数属性

读一读John Resig的简单继承模型——它应该会为你澄清问题。