Javascript 原型(prototype)语法

标签 javascript prototype

这是有效的 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;

getset 关键字是在对象文字表示法中使用的特殊运算符。您还可以使用 __defineGetter____defineSetter__:

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

虽然我不确定它是在哪个版本中引入的,但可能并非所有浏览器(尤其是 IE ;) 都支持它。

关于Javascript 原型(prototype)语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4983503/

相关文章:

javascript - AngularJS自定义指令在继承父范围的同时访问模板中的属性

javascript - Gif 动画不会在新页面上重新启动...?

javascript - 未捕获 NOT_FOUND_ERR : NOT_FOUND_ERR: DOMException 8 in Ember while using plupload

Javascript子原型(prototype)

javascript - 秒表 JavaScript

javascript - axios/express 获取/发布/放置/删除

c++ - 原型(prototype)参数名称

javascript - 函数闭包中不允许使用 .prototype 吗?

javascript - 在 jQuery 方法中使用 this

javascript - 如果我在构造函数中使用 for 循环,私有(private)变量不是特定于对象的 : JavaScript