Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

this的指向 #24

Open
AngusLius opened this issue May 3, 2018 · 0 comments
Open

this的指向 #24

AngusLius opened this issue May 3, 2018 · 0 comments

Comments

@AngusLius
Copy link
Owner

AngusLius commented May 3, 2018

作为普通函数调用

function test(name) {
    console.log(name)
    console.log(this)
}
test('Jerry')  

调用语法糖,完整的写法如下:

function test(name) {
    console.log(name)
    console.log(this)
}
test.call(undefined, 'Tom')

此时的this总是指向全局对象。在浏览器的JavaScript里,这个全局对象是window对象。
在ECMAScript 5 的strict 模式下,这种情况下的this 已经被规定为不会指向全局对象,而
是undefined

对象中函数调用

const obj = {
    name: 'Jerry',
    greet: function() {
        console.log(this.name)
    }
}
obj.greet()  // 如下的语法糖
obj.greet.call(obj) 

还可以手动指定this

obj.greet.call({name: 'Spike'})  //打出来的是 Spike

构造函数注意点:

如果构造器显式地返回了一个object 类型的对象,那么此次运算结果最终会返回这个对象,而不是我们之前期待的this:

var MyClass = function(){
  this.name = 'sven';
  return { // 显式地返回一个对象
    name: 'anne'
  }
}
var obj = new MyClass()
alert ( obj.name ); // 输出:anne

箭头函数的this

“箭头函数”的this,总是指向定义时所在的对象,而不是运行时所在的对象。

参考链接:
https://juejin.im/post/5aa1eb056fb9a028b77a66fd

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant