js進階學習之--面向對象(一)
構建對象的方式一共有三種:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>面向對象</title>
<script>
//1.工廠方式構建對象
//弊端:通過工廠構建對象無法檢測該示例來自於哪個對象類型
function Person(name,sex,age){
var obj = new Object();
obj.name = name;
obj.sex = sex;
obj.age = age;
obj.eat = function(){
console.log("喫飯");
}
return obj;
}
var person = createObj("李四","女",28);
console.log(person);
//2.字面量形式創建對象(屬性、方法)
var person = {
name:"張三",
sex:"男",
age:30,
eat:function(){
console.log("喫飯");
},
say:function(){
console.log("說話");
}
};
console.log(person);
//3.通過構造函數構建對象
//1)、構造函數名首字母大寫(規範)
//2)、構造函數和函數調用方式不同
//普通函數調用:函數名()
//構造函數調用:使用new 函數名(); 一旦使用new關鍵調用函數,內部this指向發生變化,並且該函數變成了對象,this指向是該對象本身。
function Person(){
this.name = "張三";
this.sex = "男";
this.age = 30;
this.eat = function(){
console.log("喫飯");
}
}
//Person.abc = "123"; // 靜態屬性賦值:調用方式構造函數名.屬性名 = 數據
var person = new Person();
//動態屬性:調用方式通過實例名.屬性名
console.log(person);
//console.log(Person.abc); // 靜態屬性取值:調用方式構造函數名.屬性名
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>面向對象2</title>
<script>
//如果將方法放在構造函數中就會造成多餘內存的消耗(內存冗餘)
//原因:在創建該對象多個實例時,每個方法都會形成該示例的副本並在內存中重複開闢空間
function Person(name,sex,age){
this.name = name;
this.sex = sex;
this.age = age;
this.hobby = ["看書","聽歌"];
}
//向原型對象中添加方法有2種方式:
//1.利用原型對象動態創建屬性添加方法
Person.prototype.eat = function(){
console.log("喫飯");
}
Person.prototype.say = function(){
console.log("說話");
}
console.log(Person.prototype);
//2.利用重寫原型對象添加方法
Person.prototype = {
constructor:Person,
eat:function(){
console.log("喫飯");
},
say:function(){
console.log("說話");
}
};
console.log(Person.prototype);
//對象實例會共享該實例構造函數中的原型對象
var person1 = new Person("張三","男",30);
console.log(person1);
var person2 = new Person("李四","女",28);
//在構建對象時,將方法存儲到該對象的原型對象即可解決方法造成的內存冗餘問題
</script>
</head>
<body>
</body>
</html>