这是有效的 Javascript 语法吗?它有什么作用?
Parser.prototype = {
// ...
get currentState() {
return this.state[this.state.length - 1];
},
// ...
}
参见 https://github.com/LearnBoost/stylus/blob/master/lib/parser.js .
谢谢!
最佳答案
它定义了一个getter :
Binds an object property to a function that will be called when that property is looked up.
了解 Getters and Setters .
当您访问属性时调用此函数:
var sth = obj.currentState
注意它不是一个函数调用(没有()
),而是一个普通的属性访问。
一个对应的setter看起来像这样:
set currentState(value) {
// do something with value
// value would be 42 in the next example
}
并且会在您为该属性赋值时调用,例如
obj.currentState = 42;
get
和set
关键字是在对象文字表示法中使用的特殊运算符。您还可以使用 __defineGetter__
和 __defineSetter__
:
Parser.prototype.__defineGetter__('currentStatus', function() {
return this.state[this.state.length - 1];
});
虽然我不确定它是在哪个版本中引入的,但可能并非所有浏览器(尤其是 IE ;) 都支持它。
关于Javascript 原型(prototype)语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983503/