首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript自动getter/setters (John Resig Book)

Javascript自动getter/setters (John Resig Book)
EN

Stack Overflow用户
提问于 2008-12-18 12:46:00
回答 8查看 12.4K关注 0票数 19

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

它成功了!

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

附言:我强烈推荐这本书。

编辑:

正在做什么:

var me = this;

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

我还觉得奇怪的是,它不需要修改就能在window对象上工作……

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

感谢大家的反馈!+1

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/377716

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档