var iama = {};
var iamb = function(){};
if(iama instanceof Object){
console.log(typeof(iama)); //output: "object"
}
if(iamb instanceof Function){
console.log(typeof(iamb)); //output: "function"
}
var iamc = new iamb();
console.log(typeof(iamc )); //output: "object"
new function 出來的 instance 會是 object
new object 會出現 TypeError
用 prototype 定義object的變數與函式
var animal = function() {};
animal.prototype = {
bark:"woo",
legs:4,
setEat:function(){}
};
animal.prototype.name = "lucky";
var dog = new animal();
dog.bark = "wang";
dog.setEat();
用 prototype 來做繼承
//animal.prototype.constructor;
var animal = function() {
this.bark = "woo";
this.legs = 4;
this.setEat=function(){}
};
var dog = function() {
this.bark = "wang";
};
dog.prototype = new animal(); //dog繼承animal
var lucky = new dog();
console.log(lucky.bark);
console.log(lucky.legs);
* 當物件找不到指定的屬性/函式,會去他的 prototype 找,找不到時會再找 prototype 的 prototype ,一直找到最基本幾乎什麼都沒有的 Object 為止。
大致是這樣,嗯?