Javascript automatic getter/setters (John Resig Book)

前端 未结 8 635
陌清茗
陌清茗 2020-12-14 03:02

I\'m reading \"Pro Javascript Techniques\" from John Resig, and I\'m confused with an example. This is the code:

// Create a new user object that accepts an          


        
8条回答
  •  粉色の甜心
    2020-12-14 03:22

    I just modified the code a bit like this.. This one should work.. This is same as setting me=this; But a closure is required to set the value of each property properly, else the last value will be assigned to all properties.

        // Create a new user object that accepts an object of properties
        var User = function( properties ) {
          // Iterate through the properties of the object, and make sure
          // that it's properly scoped (as discussed previously)
          var THIS = this;
          for ( var i in properties ) { (function(i){
          // Create a new getter for the property
          THIS[ "get" + i ] = function() {
            return properties[i];
          };
          // Create a new setter for the property
          THIS[ "set" + i ] = function(val) {
            properties[i] = val;
          };
        })(i); }
        }
    
        // Create a new user object instance and pass in an object of
        // properties to seed it with
        var user = new User({
          name: "Bob",
          age: 44
        });
    
    // Just note that the name property does not exist, as it's private
    // within the properties object
    alert( user.name == null );
    
    // However, we're able to access its value using the new getname()
    // method, that was dynamically generated
    alert( user.getname() == "Bob" );
    
    // Finally, we can see that it's possible to set and get the age using
    // the newly generated functions
    user.setage( 22 );
    alert( user.getage() == 22 );
    

提交回复
热议问题