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

how to call methods created via prototypes in javascript?

本文关键字:原型 创建 方法 调用 javascript      更新时间:2023-09-26

我得到一个未捕获的类型错误:question1.push它不是函数

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

我想你可能正在寻找这样的东西。

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