進階-再講prototype
var a = ["yo", "whadup", "?"];
// Arrays inherit from Array.prototype
// a ---> Array.prototype ---> Object.prototype ---> null
function f(){
return 2;
}
// f ---> Function.prototype ---> Object.prototype ---> nullLast updated
var a = ["yo", "whadup", "?"];
// Arrays inherit from Array.prototype
// a ---> Array.prototype ---> Object.prototype ---> null
function f(){
return 2;
}
// f ---> Function.prototype ---> Object.prototype ---> nullLast updated
var o = {
a: {name:"k1"},
m: function(b){
return this.a + 1;
}
};
var p = Object.create(o);
// p is an object that inherits from o
p.a.name ="k2";
console.log("p.a:", p.a); // { name: 'k2' }
console.log("o.a:", p.a); // { name: 'k2' }
//有改到o.a !!代表Object.create的inherit跟一般class based的語言其實意義不一樣function Auto(name,year){
this.year=year;
this.name=name;
}
Auto.prototype.showYear = function(){
console.log(this.year);
}
function Car(name,year, model){
Auto.call(this,name,year);
this.model=model;
}
// Auto.prototype(給new物件時用)跟Auto自己的prototype property(__proto__)不一樣.
// 且這兩個在這case裡都跟this.year, this.name沒關係.
Car.prototype = Object.create(Auto.prototype);function Circle() {
// constructor;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.printSurface = function() {
// Circle implementation
}
var obj = new Circle();
if (obj instanceof Shape) {
// do something with a shape object
}function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = new Product(); // 注意這一行.
var cheese = new Food('feta', 5);