Getters \ setters for dummies

后端 未结 12 2335
说谎
说谎 2020-11-22 04:55

I\'ve been trying to get my head around getters and setters and its not sinking in. I\'ve read JavaScript Getters and Setters and Defining Getters and Setters and just not g

12条回答
  •  猫巷女王i
    2020-11-22 05:29

    I've got one for you guys that might be a little ugly, but it does get'er done across platforms

    function myFunc () {
    
    var _myAttribute = "default";
    
    this.myAttribute = function() {
        if (arguments.length > 0) _myAttribute = arguments[0];
        return _myAttribute;
    }
    }
    

    this way, when you call

    var test = new myFunc();
    test.myAttribute(); //-> "default"
    test.myAttribute("ok"); //-> "ok"
    test.myAttribute(); //-> "ok"
    

    If you really want to spice things up.. you can insert a typeof check:

    if (arguments.length > 0 && typeof arguments[0] == "boolean") _myAttribute = arguments[0];
    if (arguments.length > 0 && typeof arguments[0] == "number") _myAttribute = arguments[0];
    if (arguments.length > 0 && typeof arguments[0] == "string") _myAttribute = arguments[0];
    

    or go even crazier with the advanced typeof check: type.of() code at codingforums.com

提交回复
热议问题