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 的指向 #18

Open
MaMaFish opened this issue Mar 12, 2020 · 0 comments
Open

this 的指向 #18

MaMaFish opened this issue Mar 12, 2020 · 0 comments

Comments

@MaMaFish
Copy link
Owner

MaMaFish commented Mar 12, 2020

  • 在函数中访问 this 时, this 指向调用该函数的对象。
  • this是在函数调用时才去做绑定(箭头函数除外,箭头函数是在函数创建时就确定了)。
  • 当一个函数的调用者是构造函数(new 出来的对象), this 指向新构造出来的对象实例
a = 'global aa';

var testObj = {
    a: 'aa',
    getValArrowFuc: function() {
        var val = (() => this.a);
        return val();
    },                                 
    getVal: function() {
        var self = this;
        var val = function() {
            return self.a;
        };
        return val();
    },
    getValGlobal: function() {
        var val = function() {
            return this.a;
        };
        return val();
    }
};

console.log(testObj.getValArrowFuc()); // aa
console.log(testObj.getVal()); // aa
console.log(testObj.getValGlobal()); // global aa
@MaMaFish MaMaFish changed the title 第18题:this的指向 this 的指向 Dec 21, 2020
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