我有javascript类和2个原型方法
var proEdit = function(){
this.client;
var self = this;
}
/*
class method to load all the project releted details
*/
proEdit.prototype.loadProject = function(){
this.client = $serviceCall.setClient("getAllByProjectID","project"); // method name and service
this.client.ifSuccess(function(data){ //sucess
self.kk();
})
this.client.ifError(function(data){ //falce
console.log("error loading setting data")
})
this.client.projectID($stateParams.projectID); // send projectID as url parameters
this.client.getReq(); // get request if post then use 'postReq('jsonbody')'
return this;
}
proEdit.prototype.kk = function(){
console.log("sass");
}
在loadProject
方法内部,我使用回调函数调用api来访问数据,如果它是ifSuccess
,那么我想调用kk
原型方法。但它给了我这个错误。
angular.js:12722 TypeError: self.kk is not a function
我尝试为同一个类创建新实例,然后调用kk
函数。然后它正在运作
this.client.ifSuccess(function(data){ //sucess
var in = new proEdit();
in.kk();
})
是否因为回调而发生?我怎么能阻止这个。谢谢
答案 0 :(得分:4)
如评论所述,您应该使用.bind
<强>示例强>
window.name = "Bar"
var MyClass = function(name) {
this.name = name;
}
MyClass.prototype.notify = function() {
console.log(this.name)
}
var m = new MyClass('Foo');
setTimeout(m.notify, 2000);
setTimeout(m.notify.bind(m), 2000);
&#13;
答案 1 :(得分:1)
你可以改变这样的代码:
var proEdit = function(){
this.client;
// var self = this;
}
/*
class method to load all the project releted details
*/
proEdit.prototype.loadProject = function(){
var that = this;
this.client = $serviceCall.setClient("getAllByProjectID","project"); // method name and service
this.client.ifSuccess(function(data){ //sucess
that.kk();
})
this.client.ifError(function(data){ //falce
console.log("error loading setting data")
})
this.client.projectID($stateParams.projectID); // send projectID as url parameters
this.client.getReq(); // get request if post then use 'postReq('jsonbody')'
return this;
}
proEdit.prototype.kk = function(){
console.log("sass");
}
希望它有所帮助!
答案 2 :(得分:1)
bind
将this
传递给回调
var proEdit = function(){
this.client;
var self = this;
}
/*
class method to load all the project releted details
*/
proEdit.prototype.loadProject = function(){
this.client = $serviceCall.setClient("getAllByProjectID","project"); // method name and service
this.client.ifSuccess((function(data){ //sucess
console.log(data)
$scope.project = data.project[0];
$scope.task = data.task;
$scope.user = data.user;
$scope.balance = data.balance[0];
this.kk();
}).bind(this))
this.client.ifError(function(data){ //falce
console.log("error loading setting data")
})
this.client.projectID($stateParams.projectID); // send projectID as url parameters
this.client.getReq(); // get request if post then use 'postReq('jsonbody')'
return this;
}
proEdit.prototype.kk = function(){
console.log("sass");
}