【问题标题】:Reassigning referenced Object returned by function重新分配函数返回的引用对象
【发布时间】:2019-04-02 01:36:31
【问题描述】:

创建一个对象并从函数中返回它是可行的。

var obj = {
    color : 'green'
}

function returnObj(){
    return obj
}

console.log(JSON.stringify(obj))
>>>{color : 'green'}

以这种方式添加一个新的键值对是可行的。 对象或数组等返回值的条目是引用。

returnObj().size = "big"
console.log(JSON.stringify(obj))
>>>{color : 'green', size  : 'big'}

但重新分配一个新对象是行不通的。

returnObj() = { yellow : 'house'}
>>> ReferenceError: Invalid left-hand side in assignment

我想做的是强制函数返回左值而不是右值。 以下也不起作用。

returnObj().this = { yellow : 'house'}
console.log(JSON.stringify(obj))
>>>{"color":"green","size":"big","this":{"yellow":"house"}}

这样做的原因是,根据用户设置,需要引用不同的对象。

var data = {
house: {color: 'green'}
car : {speed: "fast"},
}

var setting = 'house'

function returnDataObj(){
return obj[setting]
}

【问题讨论】:

  • 如果returnObject() 是一个函数,那么returnObj() = { yellow : 'house'} 是无效的语法。赋值涉及变量(即varletconst)、原语、数据类型等,
  • data 对象是否始终采用给定格式?
  • 另外,您的问题是什么?您是否正在尝试编写一个函数来通过returnObj() 将一个对象重新分配给一个新对象?
  • @wentjun 我想是的。可能有解决方法,但无论如何,看到一种方法来执行以下操作会很有趣。
  • 我相信这是相关的:stackoverflow.com/questions/3709866/… 这似乎不是函数返回引用还是值的问题,而是作为赋值运算符的一部分有效的是 javascript

标签: javascript javascript-objects lvalue


【解决方案1】:

您不能以这种方式为函数赋值。您应该将参数传递给函数(returnObj) 例如

var obj = {
color : 'green'
}

function returnObj(key , value){
  obj[key] = value;
  return obj;
}

obj = returnObj("size","big");
console.log(JSON.stringify(obj))

【讨论】:

  • returnObj().size = ''big' ;已经工作了。就像我的例子一样。不需要函数。
【解决方案2】:

函数返回总是返回值而不是引用。 对象条目和数组条目是该值内的引用。

var obj = { color : 'green' }

var reference_to_obj = obj
reference_to_obj.color = 'red'
console.log(obj.color)
>>>red

function return_obj(){return obj}
return_obj().color = "blue"
console.log(obj.color)
>>>blue

所有三个都引用相同的对象内容

但我们可以将名称“reference_to_obj”重新分配给另一个值

reference_to_obj = 'string'

函数 return_obj() 的行为类似于对对象的“匿名”引用。 只知道对象/数组的内容,但不知道保存它的变量名。

return_obj() = {} //is similar to 
AnonymousReference_1231kf10h1kf1 = {} // pseudocode for illustration

解决方法:

1.将动态引用存储在变量中。不幸的是,当引用应该更改时,您必须记住调用更新函数

var objectReference;
function updateObjectReference(){
objectReference = obj[setting]
}

2.Inner Nesting:更深一层

var obj = {content : {color: green}}
returnObj().content = {size: big}

3.外部嵌套:全局对象窗口。

window[returnObjectNameString()]={size: big}

4。函数返回对象,但也可以替换它。

function returnObj(replacementObj){
if(typeof replacementObj !== 'undefined'){ obj = replacementObj }
return obj
}

5。删除所有值并分配新值。注意:它仍然是一个对象。

var props = Object.keys(returnObj());
for (var i = 0; i < props.length; i++) {
  delete returnObj()[props[i]];
}

【讨论】:

    猜你喜欢
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多