英文:
I want to understand following Javascript code to know how JS determine value of this in below code
问题
修改后的问题:我在网上找到了这个代码示例,当我执行它时,控制台没有输出任何内容。我期望它会输出“User Name”,但实际没有。我想知道为什么会这样。为什么“this”不指向新创建的对象?JavaScript 如何确定“this”的引用?如果我将普通函数更改为箭头函数会发生什么,如果我在函数内部包含完整的条件会发生什么?
function createObj() {
// 创建一个对象并从函数中返回
return {
name: "User Name",
reference: this,
};
}
// 新创建的对象分配给一个名为 user 的变量
var user = createObj();
console.info(user.reference.name);
注意:你在代码中有一个拼写错误,createUser
应该改为 createObj
才能正常执行。
英文:
Revised Question: I came across this code example online, and when I executed it, nothing was logged to the console. I expected it to log "User Name," but it didn't. I'm wondering why this is happening. Why isn't "this" pointing to the newly created object? How does JavaScript determine the reference of "this"? What will happen if I change the normal function to an arrow function, and what if I include a complete condition inside the function?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function createObj() {
// create an object and return from function
return {
name: "User Name",
reference: this,
};
}
// newly created object assigned to a user variable
var user = createUser();
console.info(user.reference.name);
<!-- end snippet -->
答案1
得分: 1
JavaScript中的this
关键字取决于它所定义的上下文。这里有一篇文章解释了this
关键字。
在你的示例中,如果你需要获取createUser
函数返回的对象的引用,可以将userRef
更改为一个函数,类似于这样:
function createUser() {
return {
name: "User Name",
userRef: function() {
return this;
},
};
}
英文:
this
keyword in Javascript depends on the context where it is defined. Here is an article explaining this
keyword
In your example, if you need to get the reference of the object that is returned by createUser
function, change userRef
to a function, something like this
function createUser() {
return {
name: "User Name",
userRef: function() {
return this;
},
};
}
答案2
得分: 0
为了使用 this
,您必须将 useRef()
视为一个函数。
function createUser() {
return {
name: "User Name",
useRef() {
return this;
},
};
}
let user = createUser();
console.log(user.useRef().name);
英文:
In order to use this
you must treat useRef()
as a function.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function createUser() {
return {
name: "User Name",
useRef(){
return this;
},
};
}
let user = createUser();
console.log(user.useRef().name);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论