这是与 Javascript 的常见混淆。很容易认为它们的行为就像其他语言中的扩展方法一样,但在 Javascript 中,更改上下文非常容易,this
以至于它经常是偶然完成的。
所以:
MyClass.prototype.myFunction = function(args)
{
// You expect [this] to refer to an instance of MyClass
this.somePropertyOfMyClass;
};
然后你可以调用它:
var x = new MyClass();
x.myFunction(args)
然而,在 Javascript 中调用函数的方式可以改变this
所指的内容:
var y = somethingElse();
x.myFunction.call(y, args); // now in myFunction [this] refers to y
更有可能的是,许多库使用this
上下文进行链接和事件 - 容易犯错误。例如在 jQuery 中:
var $thing = $('.selector');
$thing.click(x.myFunction); // now in myFunction [this] refers to $thing
x.myFunction
对于编写 jQuery 的人来说,以这种方式调用会破坏它可能并不明显。他们可以通过以下方式解决这个问题(假设他们知道实施):
$thing.click(function() { x.myFunction(); });
如果您希望自己MyClass
能够适应这样的调用,请不要使用prototype
- 而是使用对象的属性:
function MyClass() {
var self = this;
// ...
this.myFunction = function(args)
{
// [self] will always refer to the current instance of MyClass
self.somePropertyOfMyClass;
};
}
prototype
请注意,更现代的浏览器 Javascript 引擎在优化此类调用方面非常出色,因此除非您已经确定需要额外的性能,否则我不会使用just 作为优化。