首页 > 解决方案 > Javascript原型问题,如何在原型中调用没有这个的函数?

问题描述


    let Person = function (name, age) {
         this.name = name;
         this.age = age;
      };
      
      Person.prototype.testProto = function ()  {
        console.log(this.name + " == " + this.age);
      
        let xx = function() {
           console.log("in xx");
        }
      };
      
      let person = new Person("Jake",49);
      person.testProto();

如果我用“this.xx”更改“let xx”并用 person.xx() 调用它,这将起作用;

但是不使用“this”,当 person.testProto.xx() 不起作用时,怎么可能调用它?

谢谢

标签: javascriptprototype

解决方案


从函数内部返回 xx 变量。

这将调用 testProto 函数和 xx 函数而不使用this.

let Person = function(name, age) {
  this.name = name;
  this.age = age;
};

Person.prototype.testProto = function() {
  console.log(this.name + " == " + this.age);

  let xx = function() {
    console.log("in xx");
  }
  return xx;
};

let person = new Person("Jake", 49);
person.testProto()();


推荐阅读