I'm having trouble understanding the way constructors are used to create new objects. Here's some example code:
function Backpack(type) {
this.type = type;
}
Backpack.log = function() {
console.log('This is a ' + this.type + ' backpack.');
}
var smallBackpack = new Backpack('small');
console.log(smallBackpack.type);
//-> small
smallBackpack.log();
// TypeError: smallBackpack.log is not a function
What I understand is happening (and please correct me if I'm wrong) is that Backpack is being used as a constructor and returning a new object. In this instance Backpack is the prototype of smallBackpack, and contains all of the properties that will be looked up if they're not set to smallBackpack. Why is it then, that smallBackpack.log isn't present.
function Backpack(type) {
this.type = type;
}
Backpack.prototype.log = function() {
console.log('This is a ' + this.type + ' backpack.');
}
var smallBackpack = new Backpack('small');
console.log(smallBackpack.type);
//-> small
smallBackpack.log();
//-> This is a small backpack.
In this example, I found that if I set log to Backpack.prototype, then smallBackpack gets the function. I don't understand why this works and not the first example.