javascript属性访问器 [英] javascript property accessors

查看:94
本文介绍了javascript属性访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,似乎使用属性访问器并不是那么常见(例如,与其他OO语言不同,例如Java)。

In Javascript, it seems like using property accessors is not all that common (unlike in other OO languages such as Java for example).

如果我有 Person 具有名称的对象,定义为

If I have a Person object with a name, defined as

function Person(name) {
   this.name = name;
}

一个人的名字不会改变,但我确实希望能够在需要时访问它,所以我可以这样做:

A person's name is not going to change, but I do want to be able to access it when needed, so I could do something like:

function Person(name) {
   var name = name;
   this.getName = function() {
      return name;
   }
}

即使是动态语言,我认为原则是使用getter和setter应用与静态类型的OO语言相同的方式(例如封装,添加验证,限制访问等)

Even in a dynamic language, I think the principles of using getters and setters apply the same way they do to statically typed OO languages (e.g. encapsulation, adding validation, restricting access, etc)

这个问题可能会被关闭为主观的,但我很好奇为什么这种行为不会更频繁地出现(例如,如果一切都是公开的,Java开发人员就会疯狂)。

This question may get closed as subjective, but I'm curious as to why this behavior doesn't appear more often (e.g. Java developers would go crazy if everything was public).

是否有标准在javascript中执行此操作的方法?我见过 Object.defineProperty ,但并非所有浏览器都支持。

Is there a "standard" way to do this in javascript? I've seen Object.defineProperty, but not all browsers support that.

推荐答案

Javascript具有可拦截的属性访问器:

Javascript has intercept-able property accessors:

http://ejohn.org/blog/javascript-getters-and-setters/

恕我直言这是一个更好的解决方案强制执行统一访问原则比Java更严格的显式getter,但这也是该语言的简单性和不灵活性的一部分(例如Groovy允许类似的拦截)。

IMHO this is a far better solution to enforce the Uniform Access Principle than Java's more strict explicit getters, but that is also part of the simplicity and inflexibility of that language (Groovy for instance allows for similar interception).

这篇关于javascript属性访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆