[英]Calling a method of a function constructor from another function in the global scope - Javascript
我有以下函數構造函數
function myClass(funcList) {
this.markDone = function() {
console.log("Done");
}
this.execute = function() {
funcList.forEach(function(func){
func.apply(this);
});
}
}
我在全球范圍內有幾個職能
function func1() {
console.log("func 1");
}
function func2() {
console.log("func 2");
}
var arr = [func1,func2];
我可以這樣從類的上下文中調用這些函數
var ob = new myClass(arr);
ob.execute(); //this does work
如何從這些函數func1和func2調用markDone。
如果我的func1是
function func1() {
console.log("func 1");
markDone();
}
同樣對於func 2
這是行不通的。 應該不考慮這種情況?
關。
this.markDone();
this
設置不同的內部forEach
循環,所以你需要明確設置,或及早發現它並將它設置為別的東西,像that
嘗試這個:
function func1() {
console.log("func 1");
this.markDone();
}
和:
this.execute = function() {
var that = this;
funcList.forEach(function(func){
func.apply(that);
});
}
你可以這樣
function myClass(funcList) {
var myClass = this;
this.markDone = function() {
console.log("Done");
}
this.execute = function() {
funcList.forEach(function(func){
func.apply(myClass);
});
}
}
function func1() {
console.log("func 1");
this.markDone();
}
function func2() {
console.log("func 2");
}
var arr = [func1,func2];
var ob = new myClass(arr);
ob.execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.