假设我想在Javascript中使用原型模式:
function Complimenter(compliment) {
this.complimentWord = compliment;
}
Complimenter.prototype.printCompliment = function(str) {
console.log(str + " is " + this.complimentWord);
};
这似乎有道理:
var complimenter = new Complimenter("beautiful");
complimenter.printCompliment("a flower");
//prints: "a flower is beautiful"
然而,并非总是如此,因为'这个'可以被劫持成为别的东西:
var stuff = ["a flower", "the moon"];
stuff.forEach(complimenter.printCompliment); //prints:
//"a flower is undefined"
//"the moon is undefined"
关于如何使用'这个'的任何想法没有放弃' .prototype'?
到目前为止我找到的解决方案:
var _this = this
(但这不会与.prototype一起使用)complimenter.printCompliment.bind(complimenter)
您怎么看?