[英]What the best way to keep track of a javascript object reference when prototyping
what's best practice when it comes to keeping track of an object reference in javascript: 关于跟踪javascript中的对象引用的最佳实践是什么:
function class1(param) {
this.param = param;
self = this;
}
class1.prototype.method1 = function () {
console.log(self.param);
}
$('document').ready(function () {
object1 = new class1('foo');
object2 = new class1('bar');
object1.method1(); // expected: foo , actual: bar
})
http://jsfiddle.net/d7q5f/ http://jsfiddle.net/d7q5f/
Currently self appears to be global and is overridden in the constructor of object2. 当前self似乎是全局的,并在object2的构造函数中被覆盖。 I'd be very grateful if someone could offer some advice.
如果有人可以提供一些建议,我将不胜感激。
You don't need to keep track, just use this
like so: 你并不需要跟踪,只是用
this
像这样:
function class1(param) {
this.param = param;
}
class1.prototype.method1 = function () {
console.log(this.param);
}
function class1(param) {
this.param = param;
}
class1.prototype.method1 = function () {
console.log(this.param);
}
$('document').ready(function () {
var object1 = new class1('foo');
var object2 = new class1('bar');
object1.method1(); // expected: foo , actual: foo
});
Why you want to add this self
thing? 为什么要添加此
self
事物?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.