zjm*_*126 9 javascript properties
这是我的代码:
<script type="text/javascript">
var Note=function(){}
Note.prototype = {
get id()
{
if (!("_id" in this))
this._id = 0;
return this._id;
},
set id(x)
{
this._id = x;
}
}
var a=new Note()
alert(a.id)
</script>
Run Code Online (Sandbox Code Playgroud)
这种风格就像是python,
这是我第一次看到这段代码,
你能不能给我更多关于javascript中'get'和'set'的例子.
谢谢
Cha*_*ion 10
是的,它确实.ECMAScript 5中添加了此功能.
PropertyAssignment:
PropertyName : AssignmentExpression
get PropertyName() { FunctionBody }
set PropertyName( PropertySetParameterList ) { FunctionBody }
使用此语法时,需要记住以下几点.
实际使用此功能的更好方法是通过该Object.defineProperty功能.
function Person(fName, lName) {
var _name = fName + " " + lName;
Object.defineProperty(this, "name", {
configurable: false, // Immutable properties!
get: function() { return _name; }
});
}
Run Code Online (Sandbox Code Playgroud)
这允许您使用封装具有漂亮的干净对象.
var matt = new Person("Matt", "Richards");
console.log(matt.name); // Prints "Matt Richards"
Run Code Online (Sandbox Code Playgroud)
它可以在某些引擎中,并且在EcmaScript 5的规范中,因此它将来应该被更广泛地采用.该兼容性表没有照片直接解决这个问题,但它很可能会跟随defineProperties,它提供了做同一件事的API.如前所述,John Resig有一篇关于新对象和属性API的文章.
| 归档时间: |
|
| 查看次数: |
3998 次 |
| 最近记录: |