面向對象
創建對象
var box = new Object(); // 創建一個對象
box.name = 'Lee'; // 創建一個屬性並賦值
box.age = 100; //
box.run = function () { // 創建一個方法
return this.name + this.age+'運行中';
}
工廠模式
function createObject(name,age){
var obj = new Object();
boj.name = name;
obj.age = age;
obj.run = function(){
return this.name+this.age+'運行中';
}
return obj; // 返回對象引用
}
var box1 = createObject('jack',200);
var box2 = createObject('kkk',300);
var box3 = createObject('Lee',500);
alert(box1 instanceof Object);
alert(box2 instanceof Object);
alert(box3 instanceof Object);// 都是Object沒辦法分清具體是哪一個對象
構造函數
function Box(name,age){ //所有構造函數都是Object
this.name = name;
this.age = age;
this.run = function () {
return this.name+this.age+'運行中';
};
};
var box1 = new Box('Leee',300);// 實例化
構造函數沒有 new Object,但後臺會自動 var obj = Object
this 就相當於 new Object出來的對象
構造函數不需要返回對象引用,它是後臺自動返回的
構造函數也是函數,但函數名第一個字母大寫
必須 new 構造函數名(),new Box(),而這個 Box 第一個字母也是大寫的
必須使用 new 運算符
構造函數內部的方法或函數的問題
function Box(name,age){
this.age = age;
this.nae = name;
this.run = function(){
return this.name+this.age+'運行中';
}
}
var box1 = new Box('Lee',200);
var box2 = new Box('kkk',300);
alert(box1.run == box2.run);// 輸出 false,比較的是引用地址
構造函數內部的方法通過全局來實現引用一致
function Box(name,age){
this.age = age;
this.nae = name;
this.run = run;
}
function run(){
return this.name+this.age+'運行中';
}
var box1 = new Box('Lee',200);
var box2 = new Box('kkk',300);
alert(box1.run == box2.run);// 輸出 true