2016-04-25 52 views
0

假設我有以下代碼:當在JavaScript中的對象中分配curried函數時,這和自己有什麼區別嗎?

<html> 
<head> 

    <title>test</title> 
</head> 
<body> 
    <header><h1>test</h1></header> 

    <script type="text/javascript"> 
     function myFunction2Wrapper(arg1) { 
      return function() { 
       console.log("state of arg1 in a curried function is: " + arg1); 
      } 
     } 

     function MyObject() { 
      var internalState1 = "a"; 

      function myFunction1() { 
       console.log("state of internalState1: " + internalState1); 
      } 
      myFunction1(); 

      this.myFunction2 = myFunction2Wrapper(internalState1); 
      //self.myFunction2 = myFunction2Wrapper(internalState1); 

      myFunction2(); 

      //console.log(myFunction2); 

      console.log("done!"); 

     }; 

     MyObject(); 



    </script> 

</body> 
</html> 

請特別注意線路:

this.myFunction2 = myFunction2Wrapper(internalState1); 
//self.myFunction2 = myFunction2Wrapper(internalState1); 

我的問題是:是否有分配一個對象裏面咖喱函數時thisself任何區別JavaScript的?

+0

使用本地ES5'.bind()'方法來設置上下文。請參閱http://kishorelive.com/2012/02/06/currying-in-javascript-using-bind/ – Robusto

+1

如果您取消註釋'self.myFunction2 = ...'行,您會因爲'self'沒有定義。但'self'與'this'在這裏不相關,因爲'MyObject()'是唯一指向'this'的函數。是否有任何咖啡正在發生並不相關。另外,因爲你在沒有'new'的情況下調用了'MyObject()','this'的值就是'window',這意味着'this.myFunction2 = ...'創建了一個新的全局函數 - 這就是爲什麼你可以調用'myFunction2()'你的方式。 – nnnnnn

+0

'self'實際上是定義的,指的是'window.self'。 – RainingChain

回答

0

沒有self隱式上下文/參數。 self裏面的任何功能實際上是指window.self這等於window,而不是this

注意:關於全局範圍功能,this是指window

0

我想在你的代碼中,例如使用thisself的想法不清楚,self通常用於當cotext改變時。例如:

function MyClass(){ 
    this.element = 'some'; 
    this.anotherElement = []; 
} 

//now references of the properties of MyClass be with self 
MyClass.prototype.myMethod = function(e){ 
    self = this; 
    self.element.length; 
    self.anotherElement.push('4'); 
}; 
0

在JS由於this鬆散和好玩狀態下,thatself短語大多開發人員之間的優選的窩藏在他們的算法的某些階段的this值。但是應該避免使用self,因爲與that不同,self是JS中的一個關鍵字,它表示每個web worker域的全局上下文。由於工作環境中的全局作用域被稱爲self,並且作爲self訪問,所以使用self關鍵字用於其他目的應該是不鼓勵的。

相關問題