0

In JavaScript, I want to mark object A as special, so that when A is accessed by B, B can check whether A is marked so that B treats A as different from other objects. (Think that B is a serializer that processes many different objects, and A has to be serialized in a certain way.)

Now, I can either 1: set a property in A, e.g., A.special=true
2: define a method, e.g., A.isSpecial(), which if the method exists, it shows that A is special.

I know that both of these do the same thing. From the design point of view, are there any differences, which makes one preferable?

4

3 回答 3

1

从设计的角度来看,有什么区别,哪一个更可取?

布尔属性更简单,更容易测试。如果没有定义,A.special将导致undefinedwhich is falsy already。

如果要使用方法,则需要进行测试typeof A.special == "function" && A.special(),因为只有A.special()在未定义该方法时才会导致异常。

只有当您需要动态计算特殊性(它可能取决于其他属性?)并且不想在更新这些属性的同时更新布尔标志时,该方法解决方案才会更可取。但是,对于这种情况,还有一种使用 getter 属性的中间方法(如果您不需要支持旧的 IE)。

于 2013-04-04T14:34:23.703 回答
0

Accessing the property is definitely faster:

this.special = true;

But outside A's code, someone can do A.special = false. There's no way to prevent that.

Using a method forbids other objects to modify the value. In A's constructor you can define:

...
var special = true;
...
this.isSpecial = function() {return special;};

In modern browsers, there's a way to get the best of both: Object.defineProperty. So you can define a property and forbid external sources to change it:

Object.defineProperty(this, "special", {value: true, writable: false, configurable: false});

This isn't available in IE7 and lower, and in IE8 is defined only for DOM objects and using the get and set property definitions:

Object.defineProperty(this, "special", {get: function() {return true;}});

This isn't faster than calling an isSpecial method.

于 2013-04-04T14:36:00.163 回答
-1

使用属性A.special = true;会更快(尽管我怀疑这是对性能至关重要的一段代码)。

做一个方法的好处A.special = function() {...};是你得到了一个间接层,并且可以在那里放置更高级的逻辑。例如,

A.special = function() { return foo && bar && !baz ? true : false; };
于 2013-04-04T14:34:38.347 回答