假设我有以下代码:
<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 中的对象内分配柯里函数时,this
和 self
之间有什么区别吗?
没有self
隐式上下文/参数。 任何函数中使用的self
实际上是指等于window
的window.self
,而不是this
。
注意:在全局作用域函数上,this
是指window
。
我想在您放置的示例代码中,使用 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');
};
在JS中,由于this
的松散和俏皮状态,that
或self
短语在开发人员中大多首选,以在算法的某些阶段包含this
值。但是应该避免使用self
,因为与that
不同,self
是JS中的一个关键字,它表示每个Web工作线程域的全局上下文。由于工作线程上下文中的全局范围称为 self 并作为self
访问,因此不鼓励将 self 关键字用于其他目的。