如何从函数返回变量并将其作为属性分配给对象?我写了这段代码,但它说对象属性是未定义的
var ahoy = (function yes() {
var mp = {};
function oh() {
var greeting = "hello";
var advoir = "goodbye";
}
return {
greeting: greeting,
advoir: advoir
};
oh();
mp.greeting = greeting;
mp.advoir = advoir;
console.log(mp.greeting);
console.log(mp.advoir);
});
ahoy();
答案 0 :(得分:0)
将return语句移到底部。在oh函数之外定义问候语(用var mp定义)
答案 1 :(得分:0)
我的代码中几乎没有问题: -
您可以尝试以下操作: -
var ahoy = (function yes() {
function oh() {
var mp={
greeting:'greeting',
advoir:'advoir'
}
return mp;
}
mp=oh();
var greeting = mp.greeting;
var advoir = mp.advoir;
console.log(mp.greeting);
console.log(mp.advoir);
});
ahoy();
答案 2 :(得分:0)
您可以只定义变量并一次性返回对象,而不是执行函数
var ahoy = (function yes() {
return {
greeting: "hello",
advoir: "goodbye"
};
});
ahoy();
console.log(ahoy());
答案 3 :(得分:0)
此处的错误源于ahoy
函数无法访问oh
范围内的变量。
function oh() {
var greeting = "hello";
var advoir = "goodbye";
console.log(greeting); // "hello"
}
oh();
console.log(greeting); // undefined
greeting
是oh
范围的本地范围,因为它在oh
内声明,因此无法在该函数之外访问。相反,这将起作用:
var greeting;
console.log(greeting); // undefined
function oh() {
greeting = "hello";
console.log(greeting); // "hello"
}
console.log(greeting); // undefined
oh();
console.log(greeting); // "hello"
答案 4 :(得分:0)
试试这个
var ahoy = (function yes() {
var mp = {};
// declare the variable outside of function oh
var greeting, advoir;
function oh() {
greeting = "hello";
advoir = "goodbye";
}
oh();
mp.greeting = greeting;
mp.advoir = advoir;
console.log(mp.greeting);
console.log(mp.advoir);
// move return statement to end of function
return {
greeting: greeting,
advoir: advoir
};
});
ahoy();