如何在javascript中调用通过原型创建的方法?

时间:2015-11-21 05:19:51

标签: javascript object prototypal-inheritance

我得到一个未捕获的TypeError:question1.pushIt不是函数

function Question(){
  this.question = [];
}

function Push(){
}

Push.prototype.pushIt = function(array,text){
  return array.push(text);
}

Push.prototype = Object.create(Question.prototype);

var question1 = new Question();
question1.pushIt(this.question,"is 1 = 1 ?");// error

1 个答案:

答案 0 :(得分:1)

我认为您可能正在寻找类似this的内容。

JavaScript的:

function Push() {
    this.pushIt = function(array, text){
        return array.push(text);   
    }
};

function Question() {
    this.question = [];
}

Question.prototype = new Push();

var question1 = new Question();
question1.pushIt(question1.question,"is 1 = 1 ?");

console.log(question1.question); // ["is 1 = 1 ?"]
console.log(question1 instanceof Question); // true
console.log(question1 instanceof Push); // true