Last active
December 18, 2015 18:08
-
-
Save bloodyowl/5823151 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Animal(name, age){ | |
var animal = this | |
// animal is the object | |
animal.name = name | |
animal.age = age | |
return animal | |
} | |
Animal.prototype.addYears = addYears | |
function addYears(years){ | |
var animal = this | |
animal.age += years | |
} | |
function Dog(name, age){ | |
return Animal.apply(this, arguments) // $super | |
} | |
Dog.prototype = Object.create(Animal.prototype) // inherits | |
Dog.prototype.constructor = Dog // prevent it from being Animal | |
Dog.prototype.sayHello = sayHello | |
function sayHello(){ | |
return "woof, I'm " + this.name | |
} | |
// animals won't have .sayHello, unless they're dogs | |
var zebra = new Animal("foo", 3) | |
, dog = new Dog("bar", 2) | |
typeof dog.sayHello // "function" | |
typeof zebra.sayHello // "undefined" | |
dog.sayHello() // "woof, I'm bar" | |
/* prototype is shared */ | |
Dog.prototype.sayHello = null | |
dog.sayHello // null | |
/* owned properties aren't */ | |
dog.sayHello = sayHello | |
typeof dog.sayHello // "function" | |
var otherDog = new Dog("baz", 2) | |
otherDog.sayHello // null | |
Object.prototype.hasOwnProperty.call(otherDog, "sayHello") // false (only in [[Prototype]]) | |
Object.prototype.hasOwnProperty.call(dog, "sayHello") // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment