gpt4 book ai didi

javascript-objects - 获取一个对象的名称作为 this 的值

转载 作者:行者123 更新时间:2023-12-04 11:01:25 25 4
gpt4 key购买 nike

我试图在脚本的不同点理解 this 的值(value)。与我类似的问题已在本论坛中得到解答,但这些答案远高于我目前的学习水平。

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

此代码返回要执行的前 3 个日志命令的预期 Window 对象,但仅返回从对象的方法执行的第 4 个命令的对象字面量。

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,2,3 中反射(reflect)的内容。

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

因此,它为您提供了一种在静态对象中调用元素的方法。
另一种理解方式 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

关于javascript-objects - 获取一个对象的名称作为 this 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58774697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com