Skip to content

Commit 8f12c2b

Browse files
committed
Merge pull request chuanxshi#28 from eliperelman/patch-1
Proposing that users can also prevent this error by guaranteeing instances
2 parents 80c30ed + 3305bf1 commit 8f12c2b

1 file changed

Lines changed: 19 additions & 0 deletions

File tree

literals-and-constructors/enforcing-new.html

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,25 @@
2525
var good_morning = new Waffle();
2626
console.log(typeof good_morning); // "object"
2727
console.log(good_morning.tastes); // "yummy"
28+
29+
// preferred
30+
// You can also guarantee that this situation never occurs by guaranteeing new instances;
31+
// Similar to how you can call $() and $.Deferred() in the same way as new $() and new $.Deferred():
32+
function Waffle() {
33+
if (!(this instanceof Waffle)) {
34+
return new Waffle();
35+
}
36+
37+
this.tastes = "yummy";
38+
}
39+
40+
var good_morning = new Waffle();
41+
var good_evening = Waffle();
42+
43+
console.log(typeof good_morning); // "object"
44+
console.log(good_morning.tastes); // "yummy"
45+
console.log(typeof good_evening); // "object"
46+
console.log(good_evening.tastes); // "yummy"
2847
</script>
2948
</body>
3049
</html>

0 commit comments

Comments
 (0)