函数内部的“this”与函数无关
`this` inside function has nothing to do with a function?
var f2 = undefined
var f1 = function () {
f2 = this
console.log('here')
}
f1()
f2()
输出
f2()
^
TypeError: undefined is not a function
如何从 f2(( 内部将 f1 设置为 f1?
这实际上不是设置它的正确方法,但即使是这样,您也从未调用过f1
,因此f2
的值永远不会改变。您将需要这个:
var f2 = undefined;
var f1 = function () {
f2 = this;
console.log('here');
}
f1();
f2();
也就是说,上述方法仍然不起作用,因为独立函数内部this
不是函数。在浏览器中,它将是window
对象,你会得到类似 TypeError: object is not a function
.在其他上下文(例如,node.js(中,这将取决于它们如何实现顶级对象(如果有的话(。
有一个很好的问题解释了函数如何使用this
关键字。在这种情况下,如果不按名称引用外部函数或更改调用f1
的方式,您将无法执行此操作:
// Referring to f1 by name..
var f2 = undefined;
var f1 = function () {
f2 = f1;
console.log('here');
}
f1();
f2();
// .. or using the apply method to change the value of "this", though still
// referring to f1 by name in some sense (at the call site)
var f2 = undefined;
var f1 = function () {
f2 = this;
console.log('here');
}
f1.apply(f1);
f2();
旁注,分号省略号很恶心。
我不确定没有包装器有什么方法可以做到这一点。
var wrapper = {}
wrapper.f1 = function () {
wrapper.f2 = wrapper.f1
console.log('invoked', this)
}
wrapper.f1()
wrapper.f2()
我不确定这是否适用于您的实际用例。
var whatIsThis = function() {
console.log('invoked', this)
}
whatIsThis()
在相关说明中,第二个示例显示了浏览器中的窗口对象。我不确定它会在节点中显示什么。
相关文章:
- 在另一个函数中使用变量this
- JavaScript 中的嵌套函数和 “this” 关键字
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- 为什么在这种情况下,“This”确实充当javascript函数中的私有成员
- TypeError:this.getAttribute不是一个函数-javascript
- CasperJS error - undefined 不是函数 (this.waitForUrl)
- AngularJs服务函数this()
- 内联onclick函数(this)不调用jQuery方法
- jQuery自定义函数- this.each
- 为什么在构造函数'this'DOMWindow
- 调用匿名函数'this'从函数
- Javascript检查函数(this)的长度
- 如何使用onchange="函数(this.value)
- 改变一个函数"this"值
- javascript构造函数this is't绑定正确
- JS原型函数'this'混乱