不确定标题是否清晰
以下是我的尝试,但我没有得到答案
SyntaxError:意外令牌'}'。
您如何解决?
function CreateSuspectObjects(name) {
function speak(){
return `my name is `+ name;
}
return {
name: name,
color: name.split(' ')[1],
speak()
};
};
答案 0 :(得分:3)
speak()
应该分配给对象中的键:
function CreateSuspectObjects(name) {
function speak(){
return `my name is `+ name;
}
return {
name: name,
color: name.split(' ')[1],
speak: speak()
};
};
console.log(CreateSuspectObjects('x'));
或者您可以通过删除括号来返回对函数的引用:
function CreateSuspectObjects(name) {
function speak(){
return `my name is `+ name;
}
return {
name: name,
color: name.split(' ')[1],
speak: speak
};
};
console.log(CreateSuspectObjects('x'));
答案 1 :(得分:1)
之所以发生这种情况,是因为对象中的第三项是函数调用,而不是键值对。您需要使用类似speak: speak()
的东西:
function CreateSuspectObjects(name) {
function speak(){
return "my name is " + name;
}
return {
name: name,
color: name.split(' ')[1],
speak: speak()
}
}
let obj = CreateSuspectObjects("Earl");
console.log(obj.speak);
答案 2 :(得分:0)
希望它能对您有所帮助。
function CreateSuspectObjects(name) {
speak = function() {
return "my name is: "+name;
}
return {name: name,
color: name.split(' ')[1],
speak: speak()}
}
TestResult();
function TestResult() {
console.log(CreateSuspectObjects("tran minh huynh"));
}