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

闭包那一章有疑惑,望解答 #14

Closed
tboevil opened this issue Oct 28, 2016 · 5 comments
Closed

闭包那一章有疑惑,望解答 #14

tboevil opened this issue Oct 28, 2016 · 5 comments

Comments

@tboevil
Copy link

tboevil commented Oct 28, 2016

javascript-lessons/2.4-Scope&Closure/README.md
您好,今天刚好重新看了javascript权威指南,根据此书8.2章中的解释

当函数以函数调用时,根据ECMAScript3和非严格的ECMAScript5对函数调用的规定,调用上下文(this的值)是全局对象,然而,在严格模式下,调用上下文则是undefined

而您所说指向调用函数的那个对象,函数也是一个对象,当在一个函数中调用另一个函数时,this仍然指向的是全局对象,您看是否有歧义
BTW,能否提个建议把构造函数中的this做下解释,这段我也看了好久才看懂...

@stone0090
Copy link
Owner

朋友,感觉是你错误的理解 「当函数以函数调用时」 的意思,这句话的意思是:当一个在全局作用域中定义的函数被调用时。如以下代码所示:

function func1() {
    return this;
}

var obj = {};
obj.func2 = function() {
    return this;
};

console.log(func1() === window;) // 当函数以函数调用
console.log(obj.func2() === obj;) // 当函数以对象的方法调用

所以在全局作用域中调用函数 func1() 等同于 window.func1(),所以函数 func1() 中的 this 是指向 window,也就是指向全局对象。

至于你对构造函数中的 this 有疑问,建议先看看下一个章节原型及原型链,应该就能解答你的疑惑了。

@stone0090 stone0090 reopened this Oct 30, 2016
@stone0090
Copy link
Owner

疑问:那这样的话里面的this按照您的意思应该是调用函数那个对象,也就是func1,而实际上却是window

function func1() {
    function func2() {
        console.log(this)
    }
}

首先,你给出的这个代码片段没有执行语句,并不能判断 this 的值到底是 func1 还是 window,我猜测你想像下面这样调用:

function func1() {
    function func2() {
        console.log(this)
    }
    return func2;
}
func1()();  // window

因为这样会让人觉得,是 func2() 是被 func1() 所调用的,但实际上并不是这样。上面代码的执行过程如下:

  • func1() 在全局作用域下被执行,然后返回一个函数 func2()
  • 因为 func1() 只是函数不是对象,func1() 已经执行完了,就相当于已经不存在了。
  • 然后,继续执行 func2(),此时的 func2() 不会受到已经不存在的 func1() 的影响,也是处于全局作用域下的,所以最终结果 this 是指向 window 的。

如果想让 func2() 中的 this 指向 func1(),可以把以上代码作如下改造:

function func1() {}
func1.func2 = function() {
    console.log(this)
}
func1.func2();  // func1(){}

@tboevil
Copy link
Author

tboevil commented Nov 21, 2016

@stone0090 谢谢您,我重新理了一遍思路 现在理解了

@tboevil tboevil closed this as completed Nov 21, 2016
@jiamianmao
Copy link

懂了!谢谢大湿胸

@Fromzero828
Copy link

好牛啊

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

4 participants