假设我有以下代码:
<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);
我的问题是:在JavaScript中的对象中分配curried函数时,this
和self
之间是否有任何区别?
答案 0 :(得分:0)
没有self
隐式上下文/参数。在任何函数中使用的self
实际上是指window.self
,它等于window
,而不是this
。
注意:在全局范围函数中,this
引用window
。
答案 1 :(得分:0)
我想在您举例的代码中,使用this
和self
的想法并不清楚,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');
};
答案 2 :(得分:0)
In JS due to the loose and playful state of this
, the that
or self
phrases are mostly preferred among developers to harbor the this
value at certain stages of their algorithm. However using self
should be avoided since unlike that
, self
is a keyword in JS which represents the global context of the each web worker domain. Since the global scope in the worker context is called self and accessed as self
using self keyword for other purposes should be discouraged.