“this” inside an anonymous function?

前端 未结 4 1605
猫巷女王i
猫巷女王i 2020-12-11 17:31

Inside John Resig\'s book \"Pro Javascript techniques\" he describes a way of generating dynamic object methods with the below code:

// Create a new user obj         


        
4条回答
  •  鱼传尺愫
    2020-12-11 18:01

    Here is how to do it. You need to save the context into another variable. The other option is not to do this inner function that you are doing in the for loop.

    // Create a new user object that accepts an object of properties
    function User( properties ) {
       // Iterate through the properties of the object, and make sure
       // that it's properly scoped (as discussed previously)
       var that = this;
       for ( var i in properties ) { (function(){
           // Create a new getter for the property
           that[ "get" + i ] = function() {
              return properties[i];
           };
           // Create a new setter for the property
           that[ "set" + i ] = function(val) {
               properties[i] = val;
           };
        })(); }
    }
    

    Option 2:

    // Create a new user object that accepts an object of properties
    function User( properties ) {
       // Iterate through the properties of the object, and make sure
       // that it's properly scoped (as discussed previously)
       for ( var i in properties ) {
           // 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;
           };
        }
    }
    

提交回复
热议问题