2015-02-07 103 views
1

爲什麼這個作品的時候,我從的NodeJS推出:的NodeJS的未定義 'toUpperCase'(從打字稿生成)

var a = function (name) { 
     return "Hello, " + name.toUpperCase(); 
    }; 
var result = a("bob"); 

console.log(result) 

但這:

var A = (function() { 
    function A(msg) { 
     this.msg = " "; 
     this.msg = msg; 
    } 
    A.prototype.hello = function (name) { 
     return "Hello, " + name.toUpperCase(); 
    }; 
    A.prototype.helloToBob = function (fn) { 
     return fn.apply("Bob"); 
    }; 
    return A; 
})(); 
var test = new A("some message"); 
var msg = test.hello("Bob1"); 
var msg2 = test.helloToBob(test.hello); 
console.log(msg); 

失敗:

return "Hello, " + name.toUpperCase(); 
          ^TypeError: Cannot call method 'toUpperCase' of undefined 

即生成JS代碼/從打字稿代碼編譯。(沒有錯誤編譯)

回答

1

的問題是在這行代碼。

return fn.apply("Bob"); 

這裏有幾個問題。

  1. 的第一個參數.apply(obj, arrayOfArguments)必須要在方法調用期間this指針設置爲對象。

  2. .apply()的第二個參數是一個參數數組,而不是一個參數。

在這裏你使用this爲對象,並切換到fn.call()因爲fn.apply()需要的參數數組一個可能的解決方案,但你有一個參數。

更改此:

return fn.apply("Bob"); 

這樣:

return fn.call(this, "Bob"); 

而且,所有的代碼放在一起:

var A = (function() { 
    function A(msg) { 
     this.msg = " "; 
     this.msg = msg; 
    } 
    A.prototype.hello = function (name) { 
     return "Hello, " + name.toUpperCase(); 
    }; 
    A.prototype.helloToBob = function (fn) { 
     return fn.call(this, "Bob"); 
    }; 
    return A; 
})(); 
var test = new A("some message"); 
var msg = test.hello("Bob1"); 
var msg2 = test.helloToBob(test.hello); 
console.log(msg); 

僅供參考,還有其他的解決方案。你也可以這樣做:

var A = (function() { 
    function A(msg) { 
     this.msg = " "; 
     this.msg = msg; 
    } 
    A.prototype.hello = function (name) { 
     return "Hello, " + name.toUpperCase(); 
    }; 
    A.prototype.helloToBob = function (fn) { 
     return fn("Bob"); 
    }; 
    return A; 
})(); 
var test = new A("some message"); 
var msg = test.hello("Bob1"); 
var msg2 = test.helloToBob(test.hello.bind(test)); 
console.log(msg); 
1

因爲你應該傳遞給apply()的第一個參數是上下文對象,所以它不是函數本身的第一個參數。檢查文檔。

由於helloToBob()的A類方法,我認爲,你打算在當前對象的情況下調用FN,這是你所追求的:

A.prototype.helloToBob = function (fn) { 
    return fn.apply(this, ["Bob"]); 
}; 

// or, since you have a single static argument, use function.call instead: 

A.prototype.helloToBob = function (fn) { 
    return fn.call(this, "Bob"); 
}; 
+0

'。適用()'接受一組參數,而不是一個參數。 – jfriend00 2015-02-07 05:24:12

+0

糟糕,你是對的!我非常專注於上下文,我忘記了簽名。感謝@ jfriend00的更正,我編輯了我的答案。 – 2015-02-07 05:28:35

相關問題