'这'关键字对原型不可靠

时间:2017-08-28 16:04:42

标签: javascript prototype this

假设我想在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一起使用)
  • 使用.bind(),但它很丑陋且多余:complimenter.printCompliment.bind(complimenter)

您怎么看?

0 个答案:

没有答案
相关问题