請看下面的代碼並解釋:我做錯了什麼?我不明白JavaScript中call()方法的要點
function doStuff(a, b){ return a + b + 1 ; } var myContext = { c: 1, d: 3 }; // myContext = this (result => 5) doStuff.call(myContext,myContext.c,myContext.d) // ... so why doesn't the below work? (result => NaN) doStuff.call(myContext,this.c,this.d) // To make the above work, i must replace "this" with "myContext" (result => 5)... doStuff.call(myContext,myContext.c,myContext.d) // ...which is no different to... doStuff(myContext.c,myContext.d) // ...so what was the point of call() method?
我是厚厚的嗎?
'Function.prototype的.call()在函數內部設置this,所以如果你有函數doStuff(){return this.a + this.b + 1}',你可以執行'doStuff.call(myContext);' – raser
函數*這個*是一個參數是其[*執行上下文*](http://ecma-international.org/ecma-262/5.1/#sec-10.3)的一部分,它本身不是「上下文」。 – RobG