简体   繁体   English

Javascript - 分配函数返回的引用值

[英]Javascript - Assign value of reference returned by function

I have a function of the prototype of an object called getComponent which returns this.components[name]我有一个名为getComponent的对象原型的函数,它返回this.components[name]

function Foo()
{
    this.components = {"Scripts": [...], "Sprites": [...], "States": {...}, etc };
}

Foo.prototype.getComponent = function(name)
{
    return this.components[name];
}

Then I have some code that gets a component and sets it to something else...然后我有一些代码来获取一个组件并将其设置为其他东西......

var foo = new Foo();
foo.getComponent("Sprites") = [];

This obviously raises the Uncaught ReferenceError: Invalid left-hand side in assignment .这显然会引发Uncaught ReferenceError: Invalid left-hand side in assignment

Is there anyway to set the value of the returned value?反正有没有设置返回值的值?

I don't want to access the objects variables directly: foo.components.Sprites = [] .我不想直接访问对象变量: foo.components.Sprites = []

Thanks in advance,提前致谢,

David大卫

No.没有。

You can assign values to variables, constants and to the properties of objects.您可以为变量、常量和对象的属性赋值。

A function returns a value.函数返回一个值。 It never returns a variable, constant or property (not even if it reads one of those to get the value).它从不返回变量、常量或属性(即使它读取其中之一以获取值也不返回)。


Either:要么:

  • create a setComponent method which takes two arguments and assigns the value of the second one to the property.创建一个setComponent方法,它接受两个参数并将第二个参数的值分配给属性。
  • rename your method to component and have it take an optional second argument and then act as either setComponent or getComponent depending on how many arguments were passed.将您的方法重命名为component并使其采用可选的第二个参数,然后根据传递的参数数量充当setComponentgetComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM