简体   繁体   English

为什么引用'this'会返回值,它应该是未定义的?

[英]Why does reference to 'this' return the value, it should be undefined?

I have the module... 我有模块......

var myModule = (function(){

    var obj = new Object();
    obj.name = "";
    obj.sayName = function(){
        obj.name = "jon";
        console.log(obj.name); 
        console.log(this.name);  
    }
    return obj;

})()

myModule.sayName();

This prints the word 'jon' twice as per the console.log statements. 这会根据console.log语句打印两次“jon”。

However I don't really understand why 'this' is correct since it would return the reference to the function and be 'undefined' wouldn't it? 但是我真的不明白为什么'this'是正确的,因为它会返回对函数的引用并且'undefined'不是吗?

You are calling myModule.sayName() so this inside sayName is myModule . 你正在调用myModule.sayName()所以this sayName里面是myModule

The value of myModule is copy of the object reference from obj (since that is what is returned from the anonymous IIFE). myModule的值是来自obj的对象引用的副本(因为这是从匿名IIFE返回的内容)。

Therefore obj.name and this.name are the same value. 因此obj.namethis.name是相同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM