一个简化的例子:
// Let's create a new object
function MyObject() {
//
}
// Add some method to this object
MyObject.prototype.myFunctionA = function() {
//
}
// Another method
MyObject.prototype.myFunctionB = function(arg) {
// AJAX GET request
$.get('script.php', { par : arg }, function(data) {
// and here in the callback function
// I need to call MyObject.prototype.myFunctionA method!
// but "this" references callback function so
// I don't know how to access MyObject here
});
}
Run Code Online (Sandbox Code Playgroud)
我在评论中解释了我的问题.我怎样才能做到这一点?
最简单的:
// Let's create a new object
function MyObject() {
//
}
// Add some method to this object
MyObject.prototype.myFunctionA = function() {
//
}
// Another method
MyObject.prototype.myFunctionB = function(arg) {
// AJAX GET request
var me = this;
$.get('script.php', { par : arg }, function(data) {
// use me.something instead of this.something
});
}
Run Code Online (Sandbox Code Playgroud)
可重用(使用范围陷阱):
function createDelegate(obj, handler)
{
return function() {
handler.apply(obj, arguments);
}
}
Run Code Online (Sandbox Code Playgroud)
然后
MyObject.prototype.myFunctionB = function(arg) {
// AJAX GET request
var me = this;
$.get(
'script.php',
{ par : arg },
createDelegate(this, function(data) {
// use this.something
})
);
}
Run Code Online (Sandbox Code Playgroud)
因此,与下面的注释相关的一些代码,createDelegate也可以以几种不同的方式使用,其中一种方式是:
function createDelegate(obj, handler)
{
handler = handler || this;
return function() {
handler.apply(obj, arguments);
}
}
Function.prototype.createDelegate = createDelegate;
Run Code Online (Sandbox Code Playgroud)
这允许你做以下事情:
var someObj = {a:1, b:function() {return this.a;}};
var scopedDelegateForCallback = someObj.b.createDelegate(whateverobj)
Run Code Online (Sandbox Code Playgroud)
你也可以做父母的伎俩,但这对我来说太麻烦了.
或者,你可以做这样的事情:
function createDelegate(handler, obj)
{
obj = obj || this;
return function() {
handler.apply(obj, arguments);
}
}
Object.prototype.createDelegate = createDelegate;
Run Code Online (Sandbox Code Playgroud)
并使用它:
someObj.createDelegate(someObj.b);
Run Code Online (Sandbox Code Playgroud)
或者可能:
function createDelegateForMember(handlerName, obj)
{
obj = obj || this;
return function() {
obj[handlerName].apply(obj, arguments);
}
}
Object.prototype.createDelegate = createDelegateForMember;
Run Code Online (Sandbox Code Playgroud)
然后
someobj.createDelegate("b");
Run Code Online (Sandbox Code Playgroud)
您可以在调用$ .get之前在MyObject.prototype.myFunctionB中指定"var self = this",然后您可以在回调中使用别名"self".
MyObject.prototype.myFunctionB = function(arg) {
var self = this;
$.get('script.php', { par : arg }, function(data) {
alert(self);
});
}
Run Code Online (Sandbox Code Playgroud)