开发者

C# get set javascript equivalent

开发者 https://www.devze.com 2023-04-09 19:43 出处:网络
is there an equivalent in javascript to the following C# code public class Class { public string str { get;

is there an equivalent in javascript to the following C# code

public class Class
{
    public string str
    {
        get;
        set;
    }
}

I am trying to do something like this

    var list = function () {
        this.settings = {
            id: 1
        };
        this.id = //something
    }
    var List = new list();
    alert(List.id); //alerts 1
  开发者_如何学Go  List.id = 5; // should set this.settings.id = 5
    alert(List.settings.id); // alerts 5

Although this answer is good for the c# class, I still cant reference the id as follows

    var list = function() {
        this.settings = {
            _id: 0, 
            get id() { return this._id; }, 
            set id(x) { this._id = x; }
        };
        this.id = this.settings.id;
    }

    var List = new list();


    document.write(List.id + "<br />");
    List.id += 10;
    document.write(List.settings.id + "<br />");

which is probably because this.settings.id only passes the value back to this.id and not the actual object


This wiki article explains Object.defineProperties in detail http://en.wikipedia.org/wiki/Property_(programming)#JavaScript


var o = {
    _p: 5,
    get p() { return this._p; },
    set p(x) { this._p = x; }
};

Example usage - jsFiddle.net

Defining Getters and Setters - developer.mozilla.org


Yes, John Resig has a great writeup on it, the basic idea is:

function Field(val){
    var value = val;

    this.__defineGetter__("value", function(){
        return value;
    });

    this.__defineSetter__("value", function(val){
        value = val;
    });
}

Sample: http://jsfiddle.net/mu6jf/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号