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



我有以下代码:

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] }。这让我认为该函数无法访问实例属性。

如何确保此函数可以访问实例?

如果您的目标是或支持ES6语言功能,实现您想要的功能的一种方法是通过get方法与arrow function相结合。

get方法将被声明为get speak(),这意味着它可以被调用而不必进行Paradishesion。此方法将返回一个包含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方法语法和语言功能的更多信息。

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

最新更新