在consoleChrome开发人员工具的选项卡中,我输入了this,它显示了Window对象.如何this成为窗口对象?
console.log(this);Run Code Online (Sandbox Code Playgroud)
请考虑以下代码段
var firstname = "Javascript";
var lastname = "Lover - SKT";
function getName() {
this.firstname = "Sivakumar";
this.lastname = "Tadisetti";
}
console.log(firstname);
getName();
console.log(this.lastname); // How this.lastname is working here?Run Code Online (Sandbox Code Playgroud)
我已经阅读了以下StackOverflow答案
但是不明白上面的代码片段是如何工作的(我评论的那一行)
更新:
我在jsfiddle中尝试了上面的代码片段,其中输出this.firstname是未定义的.所以这就是我问这个问题的原因.但是在stackoverflow代码片段中,它运行正常
在您的函数中,this与窗口(或运行时中的全局上下文)相同.如果这是一个Class method,this会是Class instance.
您可以this通过使用bind或使用apply和指定来更改call.
var that = {}
function getTest() {
console.log(this === window ? "this is window" : "this is not window")
}
getTest()
getTest.call(that)
getTest.apply(that)
getTest.bind(that)()Run Code Online (Sandbox Code Playgroud)
如果使用lambda语法,this则this在调用时绑定并且无法更改.
let that = {}
let fn = () => {
console.log(this === window ? "this is window" : "this is not window")
}
// this is always window. You CANNOT this on a lambda.
fn()
fn.call(that)
fn.apply(that)
fn.bind(that)()Run Code Online (Sandbox Code Playgroud)
class Foo {
fn() {
console.log(this === window ? "this is window" : "this is not window")
}
// Static methods do not have a `this`, but it can be defined by call and apply, but not bind.
static fnStatic() {
console.log(this === window ? "this is window" : "this is not window")
}
}
// this is Class instance, NOT window
new Foo().fn()
// Change this from class instance to window
new Foo().fn.call(window)
new Foo().fn.apply(window)
new Foo().fn.bind(window)()
// this is undefined in a static method, unless you apply or call. YOU CANNOT BIND a static method
Foo.fnStatic()
Foo.fnStatic.call(window)
Foo.fnStatic.apply(window)
// YOU CANNOT BIND
Foo.fnStatic.bind()(window)Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |