Today I've found an exercise which I cannot solve... Google does not help. Could you give me a prompt where to find a solution?
a = new Pepper, b = new Pepper;
How to make it in a way:
a === b
true
What is the difference between new Pepper and new Pepper()? I do not get it...
答案 0 :(得分:8)
First of all there is no difference between new Pepper()
and new Pepper
apart from the fact that the last one will hurt your feelings. Thanks to Douglas Crockford if you know what I mean.
How to make a === b
? Singleton is the answer. Check this out:
function Pepper () {
if (Pepper.instance) {
return Pepper.instance
}
Pepper.instance = this;
}
a = new Pepper, b = new Pepper;
a === b
Here is jsfiddle
If you want to know more about Singletons, read this: Learning JavaScript Design Patterns
答案 1 :(得分:2)
It’s not possible to make two different objects compare as equal with ===
. There is no difference between new Pepper
and new Pepper()
, but when you call the constructor twice, it will construct two objects. Note that {} === {}
is also false
.