书中,在User的函数的for循环中,通过闭包实现getter、setter方法,但我试了一下,程序运行时报错,
user.getname() 方法不存在。如果将闭包去除,user.getname()与user.getage()方法取得的值都是44,显然不对了,可就是不知道问题出在哪边。感觉这边通过使用闭包应该是可以实现getter、setter方法,但不知道为什么使用闭包后,总是提示getname等不是一个function。代码如下:
[code="java"]
<br> // the exaple in pro JavaScript Techniques</p> <pre><code> // 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( "name:" + user.getname() + ",age:" + user.getage()); // 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 ); </script> </code></pre> <p></head><br> <body><br> </body><br> </html><br> [/code]<br> 望解决,谢谢!</p>