In a lecture called "The Way Forward", Douglass Crockford shares that he no longer uses "new" in his JavaScript, and is weaning himself off of "this&quo
I guess I would use this constructor somewhat along these lines:
Constructor for animal:
function Animal (specs) {
// starting with an empty object, since I don´t want to inherit
var that = {},
// private attribute(s)
name = specs.name,
// public method(s)
setName = function (newName) {
name = newName;
},
getName = function () {
return name;
};
// setting up my public interface
// everything else is private
that.setName = setName;
that.getName = getName;
return that;
}
Creating my animal:
var anymal = Animal({ name: "Yoshi" });
console.log(anymal.name); // undefined, since it´s private
console.log(anymal.getName()); // "Yoshi"
anymal.setName("Sanic");
console.log(anymal.getName()); // "Sanic"
Constructor for dog:
function Dog (specs) {
// now I want to inherit from Animal
// the constructor will return the public interface for Animal
var that = Animal(specs),
// private attribute(s)
bark = specs.bark,
// public method(s)
setBark = function (newBark) {
bark = newBark;
},
getBark = function () {
return bark;
},
barks = function () {
console.log(bark);
};
// these methods will be added to the Animal public interface
that.setBark = setBark;
that.getBark = getBark;
that.barks = barks;
return that;
}
Creating my dog:
var anydog = new Dog({ name: "Klonoa", bark: "Wah who!" });
console.log(anydog.getName()); // "Klonoa"
anydog.barks(); // "Wah who!"
It´s interesting to notice that an instance of Dog will reference two separate closure scopes, one from the function Animal and the other from the function Dog.
Hope it helps!