【问题标题】:Javascript automatic getter/setters (John Resig Book)Javascript 自动 getter/setter (John Resig Book)
【发布时间】:2010-09-27 12:32:39
【问题描述】:

我正在阅读 John Resig 的“Pro Javascript Techniques”,但我对一个示例感到困惑。这是代码:

// 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 ) { (function(){
  // 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;
  };
})(); }
}

// 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 );

现在在 Firebug 控制台(在 FF3 上)上运行它会抛出 user.getname() 不是一个函数。我试过这样做:

var other = User
other()
window.getname() --> this works!

它成功了!

知道为什么吗?谢谢大家!

PS:我强烈推荐这本书。

编辑:

在做:

var me = this;

似乎工作得更好一些,但是在执行“getname()”时它返回“44”(第二个属性)...

我也觉得奇怪的是它在没有修改的情况下在窗口对象上工作......

第三个问题,PEZ 解决方案和原来的有什么区别? (他不使用匿名函数)

感谢大家的反馈! +1

【问题讨论】:

  • 我通常尽量让代码尽可能简单。因此,我删除了我认为不需要的匿名函数。

标签: javascript metaprogramming


【解决方案1】:

我刚刚修改了代码有点像这样..这个应该可以工作..这与设置 me=this; 相同但是需要一个闭包来正确设置每个属性的值,否则最后一个值将分配给所有属性。

    // 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 );

【讨论】:

    【解决方案2】:

    我开始这篇文章的唯一目的是了解为什么会发生这种情况,我终于做到了。因此,如果有人对这里的“为什么”感兴趣,他们就是:

    为什么匿名函数内部的“this”会发生变化?

    一个新函数,即使它是匿名的,在一个对象或另一个函数中声明总是改变范围,在这种情况下返回到全局范围(窗口)

    解决方案: 帖子里都说了,我觉得比较清楚的是用 .call(this) 执行匿名函数

    为什么 getname() 总是返回年龄?

    当匿名函数被立即执行时,getter/setter 在它们被调用时第一次被执行。在那一刻, i 的值将始终是最后一个,因为它已经迭代了所有属性......并且将始终返回 properties[i] 这是最后一个值,在这种情况下年龄。

    解决方案:将 i 值保存在这样的变量中

     for ( i in properties ) { (function(){ 
      var j = i
      //from now on use properties[j]
    

    基本上就是这样,如果我说的有什么错误,请纠正我,因为我正在努力学习这个......

    再次感谢。

    【讨论】:

    • “解决方案:将 i 值保存在这样的变量中”(然后“var j = i”)小心!这是误导。我不确定它是否会起作用。闭包的基本作用是保持对函数外部特定变量的引用。 (续...)
    • (contd) 你(通常)需要单独的闭包来引用它们自己引用的变量的实例。 for 循环中只有一个变量“i”。我不确定“j”是否每次循环迭代都会获得一个新实例,或者 Javascript 是否重用它(在这种情况下你的解决方案失败)
    • 该解决方案有效。我已经对其进行了测试,它是唯一能满足我最初要求的产品。
    • 有趣!然后说“j”每次循环迭代都会获得一个新实例。 (至少对于您正在使用的实现,不确定这是否在 Javascript/ECMAScript 规范中,所以只是一个警告,因为这可能是依赖于实现的行为,例如在不同的浏览器上可能会有所不同)
    • 哦,没关系!您正在执行的匿名函数中复制“var j = i”。这肯定会创建一个新实例。 Javascript 有函数作用域,而不是块作用域。
    【解决方案3】:

    我认为在 JavaScript 中工作时最好不要使用 new 关键字。

    这是因为如果您随后错误地使用 new 关键字(例如:var user = User())实例化对象,*会发生非常糟糕的事情...*原因在函数中(如果实例化时没有new 关键字),this 将引用全局对象,即window...

    因此,我建议一种更好的方法来使用类对象。

    考虑以下示例:

    var user = function (props) {
        var pObject = {};
        for (p in props) {
            (function (pc) {
                pObject['set' + pc] = function (v) {
                    props[pc] = v;
                    return pObject;
                }
                pObject['get' + pc] = function () {
                    return props[pc];
                }
            })(p);
        }
        return pObject;
    }
    

    在上面的示例中,我在函数内部创建了一个新对象,然后将 getter 和 setter 附加到这个新创建的对象。

    最后,我将返回这个新创建的对象。 请注意,this 关键字不会在任何地方使用

    然后,要“实例化”user,我将执行以下操作:

    var john = user({name : 'Andreas', age : 21});
    john.getname(); //returns 'Andreas'
    john.setage(19).getage(); //returns 19
    

    避免陷入陷阱的最佳方法是一开始就不要创建它们...在上面的示例中,我避免了 new 关键字陷阱(因为我说,如果不使用 new 关键字,当它应该使用时会导致坏事发生根本不使用new

    【讨论】:

    • new 如果处理得当,并不邪恶,如seen here
    • 我从来没有真正遇到过这个问题,因为我从来没有不小心忘记使用 new。我使用命名约定,所以我 100% 知道什么时候处理一个类,什么时候不处理,即“let user = new adUserClass(apiData.rawUser);”如果它在导入等中的名称上没有 Class,请不要使用 new,非常简单。
    【解决方案4】:

    编辑:现在,改编杰森的答案,它可以工作:

    我们需要为这些值做一个闭包。这是一种方法:

    function bindAccessors(o, property, value) {
      var _value = value;
      o["get" + property] = function() {
        return _value;
      };
      o["set" + property] = function(v) {
        _value = v;
      };
    }
    

    那么 User 构造函数如下所示:

    function User( properties ) {
      for (var i in properties ) {
        bindAccessors(this, i, properties[i]);
      }
    }
    

    【讨论】:

    • 但是在窗口对象上调用函数(正如我稍后所说)确实有效,我认为循环不是问题
    • 读者注意;巴勃罗是对的。我的答案经过编辑以反映这一点。
    • 两个cmets:1)感谢您的归属(使用我的完整用户名会更清楚),现在也许有人可以为我的答案投票......? 8) 2) 您所做的一项更改非常微妙:getter 和 setter 不会修改属性哈希,而是修改其值的集合...(续)
    • 2 续)我可以将集合传递给 User 构造函数,并且集合本身不会改变。如果这是所需的功能,那么您需要在闭包中引用属性数组。
    • +1 为您解答。 (如果可以的话,我会添加 +3 来指出我的回答中的注意事项。)
    【解决方案5】:

    你可能想要这样的东西,它更具可读性:(一旦你得到一些练习,闭包很容易学习)

    function User( properties ) {
      // helper function to create closures based on passed-in arguments:
      var bindGetterSetter = function(obj,p,properties)
      {
        obj["get"+p]=function() { return properties[p]; }
        obj["set"+p]=function(val) { properties[p]=val; return this; }
      };
      for (var p in properties)
        bindGetterSetter(this, p, properties);
    }
    

    我还添加了“return this;”所以你可以这样做:

    u=new User({a: 1, b:77, c:48});
    u.seta(3).setb(20).setc(400)
    

    【讨论】:

      【解决方案6】:

      也许变量 i 被迭代中的最后一个值(“age”)“封闭”了?然后所有的 getter 和 setter 都将访问 properties["age"]。

      【讨论】:

        【解决方案7】:

        我发现了一些似乎是答案的东西,它全都与上下文有关。使用 for 中的匿名函数,更改上下文,使 'this' 引用窗口对象,是不是很奇怪?

        所以:

        function User( properties ) {
        
          for ( var i in properties ) { 
             // here this == User Object
            (function(){
             // inside this anonymous function this == window object
            this[ "get" + i ] = function() {
              return properties[i];
            };
        
            this[ "set" + i ] = function(val) {
              properties[i] = val;
            };
            })(); 
          }
        }
        

        我不知道为什么那个函数会改变执行的上下文,我不确定它应该这样做,无论如何你可以测试它在那里运行代码并尝试 window.getname() 并且它神奇地工作! :S

        之前所说的解决方案是改变上下文,可以像 J Cooper 所说的那样,传递变量“me”并使函数成为闭包,或者你可以这样做:

        (function(){
             // inside this anonymous function this == User because we called it with 'call'
            this[ "get" + i ] = function() {
              return properties[i];
            };
        
            this[ "set" + i ] = function(val) {
              properties[i] = val;
            };
         }).call(this); 
        

        无论如何,我在运行“getname”时仍然是 44...有什么想法吗?

        【讨论】:

        • 我根据我的回答改编了 Jason 的提示。现在工作。这是个好问题。 +1。
        【解决方案8】:

        正如 OP 中所写,循环中的 this 并不是应有的引用 User 对象。如果您在循环外捕获该变量,则可以使其工作:

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

        【讨论】:

          猜你喜欢
          • 2011-09-19
          • 1970-01-01
          • 1970-01-01
          • 2017-06-01
          • 2011-04-18
          • 2012-06-19
          • 1970-01-01
          • 2013-02-09
          • 1970-01-01
          相关资源
          最近更新 更多