Getters \ setters for dummies

后端 未结 12 2147
说谎
说谎 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条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 05:14

    You can define instance method for js class, via prototype of the constructor.

    Following is the sample code:

    // BaseClass
    
    var BaseClass = function(name) {
        // instance property
        this.name = name;
    };
    
    // instance method
    BaseClass.prototype.getName = function() {
        return this.name;
    };
    BaseClass.prototype.setName = function(name) {
        return this.name = name;
    };
    
    
    // test - start
    function test() {
        var b1 = new BaseClass("b1");
        var b2 = new BaseClass("b2");
        console.log(b1.getName());
        console.log(b2.getName());
    
        b1.setName("b1_new");
        console.log(b1.getName());
        console.log(b2.getName());
    }
    
    test();
    // test - end
    

    And, this should work for any browser, you can also simply use nodejs to run this code.

提交回复
热议问题