wzhudev / blog

:book:
220 stars 14 forks source link

关于this变量的访问问题 #42

Closed CSLukkun closed 3 years ago

CSLukkun commented 3 years ago
function createPerson(name){
    var o  = new Object()
    o.name = name;
    o.getName = function(){
        console.log(name)
    }
    return o
}
var o = createPerson('ok')
o.getName()

在编写代码时遇到这个问题,原本以为name不会被打印,但是被打印了. 细细思考觉得并不是作用域的问题.

function createPerson(nameone){
    var o  = new Object()
    o.name = nameone;
    o.getName = function(){
        console.log(name)
        console.log(this.name);
    }
    return o
}
var o = createPerson('lukun')
o.getName()

所以,我想验证一下是否是闭包产生的错误. 这是我认为产生这个现象的原因.

wzhudev commented 3 years ago

请不要在我的个人博客中提问问题

CSLukkun commented 3 years ago

不好意思,我将您的博客看成我自己的博客了。

发送自 Windows 10 版邮件https://go.microsoft.com/fwlink/?LinkId=550986应用

发件人: Wendell @.> 发送时间: 2021年3月26日 15:55 收件人: @.> 抄送: @.>; @.> 主题: Re: [wendellhu95/blog] 关于this变量的访问问题 (#42)

请不要在我的个人博客中提问问题

― You are receiving this because you authored the thread. Reply to this email directly, view it on GitHubhttps://github.com/wendellhu95/blog/issues/42#issuecomment-808016590, or unsubscribehttps://github.com/notifications/unsubscribe-auth/ARB63VIJRPZ3FGFFJSBLJB3TFQ4YLANCNFSM4ZXPNLMQ.