首页 文章

JavaScript - 原型函数中的Access类实例属性

提问于
浏览
1

我有以下代码:

class Pet {
    constructor(name) {
        this.petName = name;
    }
}

Pet.prototype.speak = {
    name: function() {
        console.log(this.petName);
    }
};

// -----------------------------------------------

const myPet = new Pet("Max");
myPet.speak.name();

我希望这段代码打印 Max ,而是打印 undefined .

如果我将console.log更改为 console.log(this); ,则会打印 { name: [Function: name] } . 这让我觉得该函数无法访问实例属性 .

如何确保此功能可以访问实例?

2 回答

  • 1

    如果您的目标是支持或支持ES6语言功能,那么通过 get 方法结合 arrow function 可以实现您想要的一种方法 .

    get 方法将声明为 get speak() ,这意味着可以在没有paranthesis的情况下调用它 . 此方法将返回包含 name() 箭头函数的对象 . 使用此处的箭头函数可以直接通过 this 关键字访问封闭的 Pet 实例:

    class Pet {
        constructor(name) {
            this.petName = name;
        }
        
        // Get method allows the speak method to be called without ()
        get speak() {
          return {
            // Arrow function causes this.petName to refer to petName 
            // field of this class instance 
            name: () => {
              console.log(this.petName);
            }
          }
        }
    }
     
    const myPet = new Pet("Max");
    myPet.speak.name();
    
    const yourPet = new Pet("Min");
    yourPet.speak.name();
    

    以下是get method syntax and language feature的更多信息 .

  • 2

    当你调用这样的函数时: myPet.speak.name(); 然后在函数内 this 引用 myPet.speak . 在您的情况下,这是一个具有一个属性(名称)的对象,其值是一个函数 .

    如果你使 speak 本身是一个函数而不是一个对象,并使用属性 petName 而不是 name ,它将工作:

    class Pet {
        constructor(name) {
            this.petName = name;
        }
    }
    
    Pet.prototype.speak = function() {
        // myPet has a `petName` property, but no `name` property
        console.log(this.petName);
    };
    
    const myPet = new Pet("Max");
    myPet.speak(); // this will be `myPet` inside the function
    

相关问题