代码之家  ›  专栏  ›  技术社区  ›  Charlie Fish

javascript-访问原型函数中的类实例属性

  •  1
  • Charlie Fish  · 技术社区  · 7 年前

    我有以下代码:

    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 回复  |  直到 7 年前
        1
  •  2
  •   Dacre Denny    7 年前

    如果您正在瞄准或支持ES6语言功能,一种实现您想要的功能的方法是通过 get 方法与 arrow function .

    这个 得到 方法将被声明 get speak() 这意味着它可以被称为没有偏执。此方法将返回一个包含 name() 箭头功能。使用这里的arrow函数可以访问 Pet 实例通过 this 关键字直接:

    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
  •  1
  •   Paul    7 年前

    当您调用这样的函数时: 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