let duck = {
sayName: function() {
return "The name of this duck is " + duck.name + ".";
}
};
Use this
:
let duck = {
sayName: function() {return "The name of this duck is " + this.name + ".";}
};
function Bird() {
this.name = "Albert";
this.color = "blue";
this.numLegs = 2;
}
- Capitalized name
- Use
this
to set properties on the new object it will create. - Doesn't return anything
let blueBird = new Bird();
crow instanceof Bird; // => true
Properties defined directly on the instance object.
for (let property in duck) {
}
if(duck.hasOwnProperty(property)) {
}
Bird.prototype.numLegs = 2;
Part of the constructor
- Own properties
- Prototype properties
object.constructor
Bird.prototype = {
numLegs: 2,
eat: function() {
console.log("nom nom nom");
},
describe: function() {
console.log("My name is " + this.name);
}
};
It gets erased?
Yes:
duck.constructor === Bird; // false -- Oops
duck instanceof Bird; // true, still works
Manually set the constructor when setting the prototype to an object:
Bird.prototype = {
constructor: Bird,
// ...
}
The new object's prototype is inherited from the constructor's prototype:
Bird.prototype.isPrototypeOf(duck);
typeof Bird.prototype; // yields 'object'
Yes, because a prototype is of object type, and (almost) all objects have prototypes.
let animal = Object.create(Animal.prototype);
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
let flyMixin = function(obj) {
obj.fly = function() {
console.log("Flying, wooosh!");
}
};
Inside the constructor function:
function Bird() {
let hatchedEgg = 10; // private variable
}
When a function has access to the context in which it was created
function Bird() {
let hatchedEgg = 10; // private variable
/* publicly available method that a bird object can use */
this.getHatchedEggCount = function() {
return hatchedEgg;
};
}
Immediately invoked function expression
With modules.