“this” inside an anonymous function?

前端 未结 4 1607
猫巷女王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:08

    Is this code from the book? I have the book, but I haven't read through it.

    It's an error in the book. Check the errata: http://www.apress.com/9781590597279

    Inside the anonymous function, this is the global window.

    You could make it work by adding .call(this, i) after it.

    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) {
            (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;
                };
            }).call(this, i);
        }
    } 
    

提交回复
热议问题