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

函数作用域问题 #6

Open
izuomeng opened this issue Sep 13, 2017 · 0 comments
Open

函数作用域问题 #6

izuomeng opened this issue Sep 13, 2017 · 0 comments

Comments

@izuomeng
Copy link
Owner

izuomeng commented Sep 13, 2017

1.arguments中的函数this指向当前arguments对象,验证代码如下

var length = 10
function a() {
    console.log(this.length)
}
var obj = {
    length: 5,
    method: function(fn) {
        fn()
        arguments[0]()
    }
}
obj.method(a, 1) //10, 2

上述a在arguments调用时的this指向arguments,相当于arguments.0,因此输出的是arguments.length

2.对象中的方法如果包含立即调用的函数表达式,其作用域为全局(window)对象

var number = 2;  
var obj = {  
    number: 4,  
    fn: (function(){  
        this.number *= 2;  //这里的this指向window对象
        number = number * 2;  
        var number = 3;  
  
        return function(){  
            this.number *= 2;  
            number *= 3;  
            console.log(number);  
        }  
    })()
}; 
//结果: window.number = 4, obj.number = 4

3.函数名加括号的问题

function test() {  
    this.data = 5;  
    this.log = function() {  
        console.log(this.data);  
    }  
}  
var a = new test();  
a.log();// 5  
(a.log)();// 5  
(a.log = a.log)();// undefined  
var b = a.log;  
b();// undefined,与上面情况类似
(function(){  
    a.log();// 相当于在全局执行a.log()
})();  
setTimeout(a.log, 100)// undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant