当前位置:  开发笔记 > 编程语言 > 正文

Javascript自动getter/setters(John Resig Book)

如何解决《Javascript自动getter/setters(JohnResigBook)》经验,为你挑选了0个好方法。

我正在阅读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

推荐阅读
放ch养奶牛
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有