一、由於javascript中不存在類的概念,但有特殊的構造函數,透過new關鍵字來定義,基本用法如下:
function Walker(name,miles){//定義walker類
this.name = name;
this.miles = miles;
this.output = output;
function output(){
return this.name + '走了' + this.miles + '公里';
}
}
var a = new Walker('John',10);
var b = new Walker('Ben',20);
console.log(a.output());
console.log(b.output());
二、上面的例子可以看出每當new出一個實例時output都被重新定義,此時若能讓所有的Walker類的實例都共享output的話便能更節省資源,加以修改為prototype如下:
function Walker(name, miles) { //定義walker類
this.name = name;
this.miles = miles;
}
function output() {
return this.name + '走了' + this.miles + '公里';
}
Walker.prototype.output = output;
var a = new Walker('John', 10);
var b = new Walker('Ben', 20);
console.log(a.output());
console.log(b.output());
留言
張貼留言