获取对象名称作为其值

时间:2019-11-08 22:51:20

标签: javascript-objects console.log

我试图在脚本的不同地方理解 this 的价值。这个论坛已经回答了与我类似的问题,但这些答案大大超出了我目前的学习水平。

在我的代码实验中,我正在使用console.logs返回 this 值。返回的值始终符合预期,但是返回值的格式不一致,这使我想知道为什么。

此代码返回前三个要执行的日志命令的预期Window对象,但仅返回第四个命令的对象文字,该对象文字是通过该对象的方法执行的。

var myName = {
    name: "James",
    sayName: function() {
        console.log(this, 4);
        console.log(this.name)
    }
}

console.log(this, 1);  
function myFunction() {
    console.log(this, 2);
    function nestFunction() {
        console.log(this, 3);
        myName.sayName();
    } 
    nestFunction();
}

myFunction();

我有3个问题:为什么console.log不返回对象的名称?有没有办法做到这一点?除了console.log之外,还有一种简单的方法吗?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

好的,我正在检查您的代码,以了解您的具体含义

这是为什么在某些地方与众不同的简短解释

关键字是指它所属的对象。通常,您使用它来引用全局窗口对象。这就是控制台日志1,2,3中反映的内容。

在静态javaScript对象中调用 this 将会返回javaScript对象,而不是console.log(this,4)中反映的窗口对象。

因此,它为您提供了一种在静态对象内调用元素的方法。  理解 this 关键字的另一种方法是查看构造函数。关键字

的最佳示例

this

在构造函数内

    var myObj = function(){

            function myObj(ref)
            {
                    this.name = "";
                    this.Item = "";
                    this.ref = ref;
                    this.speak();
             }

             myObj.prototype.speak =function()
             {
                     this.name = 'James';
                     this.item = 'cheese';

                     console.log(this.ref)
                     //and the constuctor object
                     console.log(this)
             }

             return myObj;
    }();

    var e = new myObj('a Refrence string');

这应该使您对 的工作原理有基本了解

这里有更多信息可帮助您入门Wschools.com

相关问题