我有一个构造函数,它注册一个事件处理程序:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', function () {
alert(this.data);
});
}
// Mock transport object
var transport = {
on: function(event, callback) {
setTimeout(callback, 1000);
}
};
// called as
var obj = new MyConstructor('foo', transport);
Run Code Online (Sandbox Code Playgroud)
但是,我无法data
在回调中访问已创建对象的属性.它看起来this
并不是指创建的对象,而是指另一个对象.
我还尝试使用对象方法而不是匿名函数:
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', this.alert);
}
MyConstructor.prototype.alert = function() {
alert(this.name);
};
Run Code Online (Sandbox Code Playgroud)
但它表现出同样的问题.
如何访问正确的对象?
我刚刚开始使用原型JavaScript,并且我很难弄清楚this
当范围发生变化时如何在原型函数内保留对主对象的引用.让我说明一下我的意思(我在这里使用jQuery):
MyClass = function() {
this.element = $('#element');
this.myValue = 'something';
// some more code
}
MyClass.prototype.myfunc = function() {
// at this point, "this" refers to the instance of MyClass
this.element.click(function() {
// at this point, "this" refers to the DOM element
// but what if I want to access the original "this.myValue"?
});
}
new MyClass();
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过以下方式执行此操作来保留对主对象的引用myfunc
:
var myThis = this;
Run Code Online (Sandbox Code Playgroud)
然后使用myThis.myValue
访问主对象的属性.但是当我有一大堆原型函数时会发生什么MyClass
?我是否必须this
在每个开头保存引用?似乎应该有一个更清洁的方式.这样的情况怎么样:
MyClass = function() {
this.elements $('.elements'); …
Run Code Online (Sandbox Code Playgroud) 我有一个javascript类,每个方法都返回一个Q
promise.我想知道为什么this
未定义method2
和method3
.有没有更正确的方法来编写此代码?
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2)
.then(this.method3);
}
MyClass.prototype.method1 = function(){
// ...q stuff...
console.log(this.options); // logs "opts" object
return deferred.promise;
};
MyClass.prototype.method2 = function(method1resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
MyClass.prototype.method3 = function(method2resolve){
// ...q stuff...
console.log(this); // logs undefined
return deferred.promise;
};
Run Code Online (Sandbox Code Playgroud)
我可以通过使用bind
:
function MyClass(opts){
this.options = opts;
return this.method1()
.then(this.method2.bind(this))
.then(this.method3.bind(this));
}
Run Code Online (Sandbox Code Playgroud)
但不完全确定为什么bind
有必要; 正在.then()
杀戮this
?
我有一个使用该setTimeout
函数的方法,并调用另一个方法.在初始加载方法2工作正常.但是,在超时后,我收到一个错误,表示method2
未定义.我在这做错了什么?
例如:
test.prototype.method = function()
{
//method2 returns image based on the id passed
this.method2('useSomeElement').src = "http://www.some.url";
timeDelay = window.setTimeout(this.method, 5000);
};
test.prototype.method2 = function(name) {
for (var i = 0; i < document.images.length; i++) {
if (document.images[i].id.indexOf(name) > 1) {
return document.images[i];
}
}
};
Run Code Online (Sandbox Code Playgroud)