简体   繁体   English

获取/设置所有可用属性(JS)

[英]get/set for all available properties (JS)

Is it possible to create get/set function for undefined properties, 是否可以为未定义的属性创建get / set函数,
like in PHP __get() and __set() ? 像在PHP __get()和__set()中一样?

You can access JavaScript object properties values using array access notation, you can also create a new property at any time using this notation or regular assignment notation. 您可以使用数组访问表示法访问JavaScript对象属性值,也可以随时使用此表示法或常规赋值表示法创建新属性。

var myObject = {};
myObject.Name = "Luis";
alert(myObject.Name);
alert(myObject["Name"]);
myObject["Name"] = "Dany";
alert(myObject.Name);

You can do 你可以做

function ClassName(arg) {
    var v = arg;
    this.getter = function {
         return v;
    };
    this.setter = function(val) {
         v = val;
    };
}

when you use it 当你使用它

var cn = new ClassName('a');
cn.setter('b');
alert(cn.getter()); /* alerts value 'b' */ 

Note that this uses the Constructor Invocation Pattern. 请注意,这使用了构造函数调用模式。 By convention, you need to declare the function/class name with capital letter to indicate that this function/class need to be declared with the 'new' keyword. 按照约定,您需要使用大写字母声明函数/类名称,以指示该函数/类需要使用“ new”关键字进行声明。 Hope this helps 希望这可以帮助

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

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