Javascript原型语法

Bet*_*lis 6 javascript prototype

这是有效的Javascript语法吗?它有什么作用?

Parser.prototype = {

  // ...

  get currentState() {
    return this.state[this.state.length - 1];
  },

  // ...

}
Run Code Online (Sandbox Code Playgroud)

请参阅https://github.com/LearnBoost/stylus/blob/master/lib/parser.js.

谢谢!

Fel*_*ing 5

它定义了一个getter:

将对象属性绑定到将在查找该属性时调用的函数.

阅读有关Getters和Setters的信息.

访问属性时调用此函数:

var sth = obj.currentState
Run Code Online (Sandbox Code Playgroud)

请注意,它不是函数调用(没有()),而是普通的属性访问.

相应的setter看起来像这样:

set currentState(value) {
  // do something with value
  // value would be 42 in the next example
}
Run Code Online (Sandbox Code Playgroud)

并且在为该属性赋值时将被调用,例如

obj.currentState = 42;
Run Code Online (Sandbox Code Playgroud)

getset关键字对象的文字符号内使用一个特殊的运营商.你也可以使用__defineGetter____defineSetter__:

Parser.prototype.__defineGetter__('currentStatus', function() {
    return this.state[this.state.length - 1];
});
Run Code Online (Sandbox Code Playgroud)

我不确定它在哪个版本中引入,它可能不受所有浏览器支持(尤其是IE;)).

  • 它是在ECMAScript 5中引入的,而IE9是第一款具有功能性ES5引擎的浏览器. (3认同)