我正在尝试做这个非常简单的测试,但它抛出错误:
Object.prototype.myMethod = function(this) { // How do I make 'this' work here?
return this.toString();
};
然后我应该可以调用它,例如:
var str = 'This should be returned back';
str.myMethod(); // Expected output: This should be returned back
最佳答案
您没有将 this
传递给该函数。它“就在那里”(找不到更好的短语来描述它)。调用像 str.myMethod()
这样的函数,str
成为函数内部的“上下文”,又名 this
。
关于javascript - 如何将 'this' 传递给原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19049920/