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 试验 #3

Open
zhenyong opened this issue Jul 10, 2019 · 0 comments
Open

拖了十年都没去做的 this 试验 #3

zhenyong opened this issue Jul 10, 2019 · 0 comments

Comments

@zhenyong
Copy link
Owner

zhenyong commented Jul 10, 2019

浏览器版本:Mac Chrome 75

全局作用域下访问 this

console.log(this) 
//strict: window
//non: window

结论:一样指向 window

全局方法里的 this

function bar() {
        console.log(this);
// strict: undefined
// non-strict: window
    }

    function foo() {
        function fun() {
            console.log(this);
// strict: undefined
// non-strict: window
        }
        fun();
    }
    bar();
    foo();

结论:严格模式下是 undefined,非严格模式下是 window

对象的方法中的 this

    var obj = {
        name: 'peter',
        foo: function () {
            return this.name;
        }
    }
    console.log(obj.foo()); // 都是 peter

结论:this 指向调用函数的对象实例

构造函数的 this

    function A() {
        this.foo = '~foo~';
        this.bar = function () {
            console.log(this.x); // 都是 x
            return this.foo;
        }
    }
    var o2 = new A();
    o2.x = 'x';
    console.log(o2.bar()); // 都是 ~foo~

结论:this 指向构造函数对应创建的对象

事件处理函数中的 this

outElement.onclick  = function (e) {
        console.log(this) // 点击里面元素,打印 out element
    }
inElement.onclick = function (e) {
        console.log(this) // 点击里面元素,打印 in element
    }

结论:两种模式,this 指向事件绑定的元素(即 e.currentTarget)

内联事件处理器

<button onclick="alert((function(){'use strict'; return this})());">strict</button>
// strict: undefined

 <button onclick="alert((function(){return this})());">non strict</button>
// non: window

结论:严格模式下,内联函数的this 是 undefined,非严格模式下指向 window

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