HTML and CSS Reference
In-Depth Information
return "bau";
};
};
What you have here is a new object named Dog . Early on, when talking about objects, you also
created something similar:
var dog = {
name: "Jerry Lee Esposito",
};
The big difference here is that the latter code snippet represents a snapshot of only data; the
former code snippet, instead, is a function with data and behavior.
So how would you use the Dog object? To use the Dog object, you need to instantiate it using the
classic new constructor, as shown below:
var jerry = new Dog("jerry");
What if you miss the new operator and go with something like this?
var jerry = Dog("jerry");
The tricky thing is that if you forget to use the new operator, you won't get any exception and your
code will just run. However, any action you perform on Dog (for example, setting the name property)
will be executed on the this object. Without the new operator in front, that would be resolved as the
global JavaScript object. This means that you are polluting the global namespace of the JavaScript
interpreter. Here's a safe countermeasure that doesn't create issues whether or not you use the new
operator:
var Dog = function(name) {
var that = {};
that.name = name;
that.bark = function() {
return "bau";
};
return that;
};
The difference is that you now explicitly create and return a new object—an object named that .
This is familiarly known as the “Use-That-Not-This” pattern.
Search WWH ::




Custom Search