總結JS物件導向

來源:互聯網
上載者:User

標籤:io   ar   color   使用   sp   java   for   資料   on   


javascript物件導向

(一)

對象其實就是一種參考型別。

而對象的值就是參考型別的執行個體。

在 JavaScript 中參考型別是一種資料結構,
將資料和功能組織在一起。

它也常被稱做為類,但 JavaScript 中卻沒有類的概念。

雖然 JavaScript 是一門物件導向的語言,
卻不具備傳統物件導向語言所支援的類和介面等基本結構。

對象的建立以及常用操作
使用 new 運算子

var user = new Object(); //使用 new 運算子建立一個對象
user.name = ‘美女‘; //給對象添加屬性
user.age = 18;
user.address = ‘成都‘;
對象字面量

var user = {
name:‘美女‘,
age:18,
address:‘成都‘
};
簡單方式(傳統賦值方式)

var user = {};
user.name = ‘美女‘; //給對象添加屬性
user.age = 18;
user.address = ‘成都‘;

屬性的調用

對於對象屬性的調用有兩種方式:

調用方法如下:

alert(user.name + " " +user.age); //返回 ‘美女 成都‘

另一種方法:

alert(user[‘name‘] + " " +user[‘age‘]); //返回 ‘美女 成都‘

添加方法

var user = { name:‘美女‘, //給對象添加屬性
age:22, address:‘成都‘,
showInfo:function(){ //添加一個方法
alert(this.name+" "+this.age+" "+this.address);
},
showHello:showHello //將對象外部的方法添加到對象
};
function showHello(){
alert(this.name+" "+this.age+" "+this.address);
}

alert("Hello!");
}
} user.showInfo(); //調用方法 user.showHello();


(二)

建立對象

我們知道,要建立一個對象我們可以用如下代碼:

var user = new Object();
user.name = ‘mm‘;
user.age = 20;
user.address = ‘樂山‘;

用這樣的方法建立對象比較簡單直觀,也是 JavaScript 種建立對象最基本的方法。
但是這樣就有一個問題,如果我們需要建立多個對象,那麼我就得寫很多重複的代碼。
比如我們想建立另一個對象 user1 ,我們就得重新將上面的代碼重新寫一遍,
這在實際開發過程中是不合適的,這樣如果對象過多,代碼量將大大增加。

為瞭解決這樣的問題,我們可以使用一種叫做原廠模式的方法,這種方法
就是為瞭解決執行個體化對象產生大量重複代碼的問題。

原廠模式

function create(name, age) {
  var obj = new Object();
  obj.name = name;
  obj.age = age;
  obj.show = function () {
    return this.name +‘ ‘+ this.age;
  };
  return obj;
}

var obj1= create(‘bclz‘, 30); //第一個執行個體
var obj2= create(‘bcxb‘, 20); //第二個執行個體
alert(obj1.show());
alert(obj2.show());

從上面的代碼我們可以看出,原廠模式解決了執行個體化時代碼大量重複的問題,
但又出現了一個問題,那就是識別問題,我們根本無法弄清楚他們到底是哪個對象的執行個體。比如

alert(typeof obj1); //Object

alert(obj1 instanceof Object); //true

以上代碼標明 obj1 是 Object 對象,但是我們無法知道具體是哪一個對象建立的。

建構函式(構造方法)

function User(name, age) { //建構函式模式
  this.name = name;
  this.age = age;
  this.show = function () {
    return this.name + ‘ ‘+this.age;
  };
}

建立對象的時候用 new 運算子就可以了:

var user1 = new User(‘mm‘, 20); //第一個執行個體
var user2 = new User(‘ss‘, 10); //第二個執行個體

現在我們就可以檢測 user1 或者 user2 是不是屬於 User。

alert(user1 instanceof User); //true

可見,使用建構函式的方法,即解決了重複執行個體化的問題,又解決了對象識別的問題。

要建立 User 對象的新執行個體,就要使用 new 操作符,使用這個方式構建執行個體對象,會經過下面 4 個步驟:

1.建立一個新對象;

2.將建構函式的範圍給新對象(因此 this 指向的這個新對象)。

3.執行建構函式內的代碼在(為新對象添加屬性);

4.返回新對象。

不過需要注意下面兩個問題:

建構函式也是函數

建構函式與函數的唯一區別,就是調用方式的不同,不過,建構函式畢竟也是函數,不存在什麼
特殊的定義建構函式的文法。任何函數,只要通過 new 操作符來調用,就可以把它看作是建構函式;
而任何函數,如果不通過 new 操作符調用,它就和普通函數沒有什麼區別,例如前面定義的 User :

//當作建構函式調用
var user1 = new User(‘mm‘, 20);
user1.show(); //ss 10;

//當作普通函數調用
User(‘mm‘, 20);
window.show(); //ss 10;

結果上沒有什麼區別,只是大家可以看到,當作普通函數調用的話,函數裡this對象的指向,
其實是指向的 window 全域對象。而通過 new 關鍵字調用,this 指向的則是新對象而已,所以,
其實還可以這麼來寫:

var o = new Object();
User.call(o,‘ss‘, 10);
o.show();

通過函數方法 call 來重新定義對象的範圍,這裡不多做解釋,講到函數細節時再仔細介紹這種方法,
這裡只是說明可以改變對象的範圍的,其實就是改變 this 的指向

建構函式的問題

建構函式的模式雖然好,但是並非沒有缺點。建構函式最大的問題就是,每個方法都要在執行個體上重
新建立一次。在前面的例子中, user1 和 user2 中都有一個 show 方法,如果我們執行以下語句:

alert(user1.show==user2.show); //結果返回的是 false

結果返回的是 false ,這就說明方法其實也是一種引用地址。如果我們同樣重複建立了多個對象,
那麼每個對象中的方法都會在記憶體中開闢新的空間,這樣浪費的空間就比較多。要解決這個問題,
我們就需要用到執行個體屬性或者方法的共用。 我們可以使用一種變通的方式,來達到我們想要的效果,
也就是讓 show 方法不再重複建立

function User(name, age) {
  this.name = name;
  this.age = age;
  this.show = show;
}
function show(){
alert(this.name + ‘ ‘ + this.age);
}
將show方法移到外部,相當於 show 方法成了一個全域函數,然後再到 User 建構函式內部去引用 show 方法
,這樣 User 內部的 this.show 都指向了同一個全域函數 show ,因此,我們執行個體化的 user1 和 user2 就
實現了共用,可以再次調用:

alert(user1.show==user2.show); //結果返回的是 true
但是這隻是一個測試,如果你要讓更多的屬性或者方法實現共用,那不是要定義更多的全域函數或
者變數,這種方式是不科學也不可行的。因此,我們需要引入另外一個javascript物件導向的重要
概念原型


(三)

Prototype 原型模式

通過建構函式的弊端引出原型概念

為了講清楚原型,我們還是必須先回顧一下建構函式的問題,
用一個簡單的例子再次講解一下,我們有一隻貓的建構函式,如下:

function Cat(name,color){
this.name = name;
this.color = color;
}

這個建構函式很簡單,不再多說,那麼現在再為這個函數添加一個不變的屬性
"type"(種類),再添加一個方法 eat(吃老鼠)。那麼,Cat 就變成了下面這樣:

function Cat(name,color){
this.name = name;
this.color = color;
this.type = "貓科動物";
this.eat = function(){alert("吃老鼠");};
}

產生執行個體:

var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat ("二毛","黑色");
alert(cat1.type); // 貓科動物
cat1.eat(); // 吃老鼠

表面上好像沒什麼問題,但是實際上這樣做,有一個很大的弊端。那就是對於每一個執行個體對象,
type 屬性和 eat() 方法都是一模一樣的內容,每一次產生一個執行個體,都必須為重複的內容,
多佔用一些記憶體。這樣既不環保,也缺乏效率。

alert(cat1.eat == cat2.eat); //false

因此,為了讓 type 屬性和 eat() 方法在記憶體中只產生一次,然後所有執行個體都指向那個記憶體位址,
引出了原型

什麼是原型?

原型對象實際上就是建構函式的一個執行個體對象,和普通的執行個體對象沒有本質上的區別。
可以包含特定類型的所有執行個體的共用屬性或者方法。 這個 prototype 的屬性值是一個對象
(屬性的集合),預設的只有一個叫做 constructor 的屬性,指向這個函數本身。

比如我們簡單定義一個 SuperType 名字的函數,裡面什麼屬性也沒有在函數內部是這個樣子的

function SuperType(){

}


從我們看到,函數裡面雖然什麼都沒有,但是有一個預設的 prototype 屬性,它是一個對象,
它指向的是自己的地址,而 prototype 這個對象本身裡面又有一個屬性 constructor ,而這個
屬性,又指向了函數本身,有點繞,你可以通過下面的代碼做一下測試,看看效果

alert(SuperType.prototype) //object
alert(SuperType.prototype.constructor) //彈出函數本身function SuperType(){
}

prototype 和 constructor 是原型最基本的概念,現在看可能還有點暈,沒關係,
我直接上以前的代碼,看看區別,還是之前的 Cat 建構函式,將它修改一下:

function Cat(name,color){
this.name = name;
this.color = color;
}
Cat.prototype.type = "貓科動物";
Cat.prototype.eat = function(){alert("吃老鼠")};

產生執行個體:

var cat1 = new Cat("大毛","黃色");
var cat2 = new Cat("二毛","黑色");
alert(cat1.type); // 貓科動物
cat1.eat(); // 吃老鼠

這時所有執行個體的 type 屬性和 eat() 方法,其實都是同一個記憶體位址,指向 prototype 對象,
因此就提高了運行效率。

alert(cat1.eat == cat2.eat); //true

Prototype 模式的驗證方法
為了配合 prototype 屬性,Javascript 定義了一些輔助方法,協助我們使用它。

isPrototypeOf()

這個方法用來判斷,某個 proptotype 對象和某個執行個體之間的關係。

alert(Cat.prototype.isPrototypeOf(cat1)); //true
alert(Cat.prototype.isPrototypeOf(cat2)); //true
hasOwnProperty()

每個執行個體對象都有一個 hasOwnProperty() 方法,用來判斷某一個屬性到底是區域屬性,
還是繼承自 prototype 對象的屬性。

alert(cat1.hasOwnProperty("name")); // true
alert(cat1.hasOwnProperty("type")); // false

in 運算子
in 運算子可以用來判斷,某個執行個體是否含有某個屬性,不管是不是區域屬性。

alert("name" in cat1); // true
alert("type" in cat1); // true

in 運算子還可以用來遍曆某個對象的所有屬性。

for(var prop in cat1) {
alert("cat1["+prop+"]="+cat1[prop]);
}

來看一下 javascript 進階程式設計 書中對與原型的描述和說明

function Person(){ } //建立Person建構函式
Person.prototype.name = "Nicholas"; //建立共用屬性name
Person.prototype.age = 29; //建立共用屬性age
Person.prototype.job = "Software Engineer"; //建立共用屬性job
Person.prototype.sayName = function(){ //建立共用函數sayName
alert(this.name);
};

//分別建立了 person1 和 person2,裡面都有 sayName 函數,並且彈出的值都是一樣

var person1 = new Person();
person1.sayName(); //"Nicholas"
var person2 = new Person();
person2.sayName(); //"Nicholas"
alert(person1.sayName == person2.sayName); //true

通過上面,可以看出,person1 和 person2 ,他們內部都有一個指向 Person.prototype 的指標,
可以通過原型的 isPrototype 方法測試一下

alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
function User(){};
var person3 = new User();
alert(Person.prototype.isPrototypeOf(person3)); //false
alert(User.prototype.isPrototypeOf(person3)); //true

作為類比,我們考慮下JavaScript 中的資料類型 - 字串(String)、
數字(Number)、數組(Array)、對象(Object)、日期(Date)等。
我們有理由相信,在 JavaScript 內部這些類型都是作為建構函式來實現的,
比如:

// 定義數組的建構函式,作為 JavaScript 的一種預定義類型
function Array() {
// ...
}

// 初始化數組的執行個體
var arr1 = new Array(1, 56, 34, 12);

// 但是,我們更傾向於如下的文法定義:
var arr2 = [1, 56, 34, 12];

同時對數組操作的很多方法(比如 concat、join、push)應該也是在 prototype 屬性
中定義的。 實際上,JavaScript所有的固有資料類型都具有唯讀 prototype 屬性
(這是可以理解的:因為如果修改了這些類型的 prototype 屬性,則哪些預定義的
方法就消失了), 但是我們可以向其中添加自己的擴充方法。

// 向 JavaScript 固有類型 Array 擴充一個擷取最小值的方法
Array.prototype.min = function() {
var min = this[0];
for (var i = 1; i < this.length; i++) {
if (this[i] < min) {
min = this[i];
}
}
return min;
};

// 在任意Array的執行個體上調用min方法
console.log([1, 56, 34, 12].min()); // 1
注意:這裡有一個陷阱,向 Array 的原型中添加擴充方法後,當使用for-in 迴圈數組時,
這個擴充方法也會被迴圈出來。 下面的代碼說明這一點(假設已經向Array 的原型中擴充了 min 方法):

var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
total += parseInt(arr[i], 10);
}
console.log(total); // NaN

解決方案也很簡單:
var arr = [1, 56, 34, 12];
var total = 0;
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
total += parseInt(arr[i], 10);
}
}
console.log(total); // 103

constructor
constructor
始終指向建立當前對象的建構函式。比如下面例子:

// 等價於 var foo = new Array(1, 56, 34, 12);
var arr = [1, 56, 34, 12];
console.log(arr.constructor === Array); // true

// 等價於 var foo = new Function();
var Foo = function() { };
console.log(Foo.constructor === Function); // true

// 由建構函式執行個體化一個obj對象
var obj = new Foo();
console.log(obj.constructor === Foo); // true

// 將上面兩段代碼合起來,就得到下面的結論
console.log(obj.constructor.constructor === Function); // true

但是當 constructor 遇到 prototype 時,有趣的事情就發生了。
我們知道每個函數都有一個預設的屬性 prototype ,而這個 prototype 的
constructor 預設指向這個函數。如下例所示:

function Person(name) {
this.name = name;
};
Person.prototype.getName = function() {
return this.name;
};
var p = new Person("ZhangSan");

console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true

// 將上兩行代碼合并就得到如下結果
console.log(p.constructor.prototype.constructor === Person); // true

當時當我們重新定義函數的 prototype 時
(注意:和上例的區別,這裡不是修改而是覆蓋) ,
constructor 的行為就有點奇怪了,如下樣本:

function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // false
console.log(Person.prototype.constructor === Person); // false
console.log(p.constructor.prototype.constructor === Person); // false

為什麼呢? 原來是因為覆蓋 Person.prototype 時,等價於進行如下代碼操作:

Person.prototype = new Object({
getName: function() {
return this.name;
}
});

而 constructor 始終指向建立自身的建構函式,所以此時
Person.prototype.constructor === Object,
即是:

function Person(name) {
this.name = name;
};
Person.prototype = {
getName: function() {
return this.name;
}
};
var p = new Person("ZhangSan");
console.log(p.constructor === Object); // true
console.log(Person.prototype.constructor === Object); // true
console.log(p.constructor.prototype.constructor === Object); // true

怎麼修正這種問題呢?方法也很簡單,重新覆蓋 Person.prototype.constructor
即可:

function Person(name) {
this.name = name;
};
Person.prototype = new Object({
getName: function() {
return this.name;
}
});
Person.prototype.constructor = Person;
var p = new Person("ZhangSan");
console.log(p.constructor === Person); // true
console.log(Person.prototype.constructor === Person); // true
console.log(p.constructor.prototype.constructor === Person); // true

對象的 _proto_ 隱式原型

上面我們建立了兩個對象, person1 和 person2 ,這兩個對象,也都指向了 Person 建構函式的原型,
這是因為每個對象都有一個隱藏的屬性——“_proto_”,這個屬性引用了建立這個對象的函數的
prototype 。
即:
person1._proto_ === Person.prototype

這個 _proto_ 是一個隱藏的屬性,javascript 不希望開發人員用到這個屬性值,有的低版本瀏覽器
甚至不支援這個屬性值。
看下面的代碼:

console.log(Object.prototype);
var obj = new Object();
console.log(obj.__proto__);

你會發現列印了相同的內容:
obj 這個對象本質上是被 Object函數建立的,因此 obj._proto_=== Object.prototype。
我們可以用一個圖來表示。
關於隱式原型,主要涉及到原型繼承的主要原理,這裡只是拋出這個概念稍作介紹

(四)

在不同範圍中
不同的函數和變數聲明的意義不同

function Person(name,age){

//在建構函式中,凡是直接用 var 來聲明的變數或者函數
//這種,一般稱之為私人變數或函數,也就意味著,只能在建構函式中使用
//不能在執行個體化對象中使用
var address = "成都";

//凡是用 this 聲明的變數或者函數,這種一般稱之為特權變數或者函數
this.name = name;
this.age = age;
}

//原型中的變數或者函數,一般稱之為公有變數或函數
//意味著所有的執行個體化對象使用的是同一個變數或者函數

Person.prototype = {
constructor:Person,
sex:"男",
show:function(){}
}

// Person.prototype.sex = "男";
// Person.prototype.show = function(){
// };

 

var user = {

}

(五)

原型(prototype)

每一個函數都有prototype,而prototype又有constructor,最終constructor又指向函數,
它們形成首尾相連的模式。

一、 建構函式綁定

先來看下面兩個函數的意義:

function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
};
}

function ClassB(sColor,sName){
this.newMethod=ClassA;
this.newMethod(sColor);
delete this.newMethod;
this.name=sName;
this.sayName=function(){
alert(this.name);
};
}

初一看,這種方式貌似很複雜,其實道理很簡單,就是在繼承的函數裡面,建立一個變數
newMethod,然後將 ClassA 的指標指向這個變數,然後在 ClassB 中調用這個方法,這樣
實際上 newMethod 引用的範圍也就是說 this 的指向就是 ClassB 執行個體化的對象了。
注意: 最後一行刪除對 ClassA 的引用,這樣以後就不能再調用它。所有的新屬性和
新方法都必須在刪除了新方法的代碼後定義,否則覆蓋超類的相關屬性和方法

為證明前邊的有效,運行下面例子

var objA=new ClassA("red");
var objB=new ClassB("blue","Nicholas");
objA.sayColor();
objB.sayColor();
objB.sayName();

由於這種繼承方法流行,ECMAScript 為 Function 對象加入了兩個新方法,
即 call() 和 apply() ,所以上面的方法完全可以使用 call 或 apply 方法進行替代,
將父物件的建構函式綁定在子物件上,即在子物件建構函式中加一行:

function ClassB(sColor,sName){
//this.newMethod=ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this,sColor);

this.name=sName;
this.sayName=function(){
alert(this.name);
};
}

這裡可以看到,前面三行的代碼直接改成了 call 方法,所以針對最上面的例子,我們改成下面的樣子,
就可以直接實現繼承了

function Cat(name,color){
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動物

二、 prototype模式

第二種方法更常見,使用 prototype 屬性。 如果"貓"的 prototype 對象,指向一個
Animal 的執行個體,那麼所有"貓"的執行個體,就能繼承 Animal 了。

Cat.prototype = new Animal();
Cat.prototype.constructor = Cat; (在函數中最後寫上這行代碼,
讓函數的prototype.constructor指向函數本身,
這樣可以防止指標的錯亂。)
var cat1 = new Cat("大毛","黃色");
alert(cat1.species); // 動物

代碼的第一行,我們將 Cat 的 prototype 對象指向一個 Animal 的執行個體。

Cat.prototype = new Animal();

它相當於完全刪除了prototype 對象原先的值,然後賦予一個新值。但是,第二行又是什麼意思呢?

Cat.prototype.constructor = Cat;

原來,任何一個 prototype 對象都有一個 constructor 屬性,指向它的建構函式。
如果沒有 "Cat.prototype = new Animal();" 這一行,Cat.prototype.constructor 是指向
Cat 的;加了這一行以後,Cat.prototype.constructor 指向 Animal 。

alert(Cat.prototype.constructor == Animal); //true

更重要的是,每一個執行個體也有一個 constructor 屬性,預設調用 prototype 對象的 constructor 屬性。

alert(cat1.constructor == Cat.prototype.constructor); // true

因此,在運行 "Cat.prototype = new Animal();" 這一行之後,cat1.constructor 也指向 Animal

alert(cat1.constructor == Animal); // true

這顯然會導致繼承鏈的紊亂( cat1 明明是用建構函式 Cat 產生的),因此我們必須手動糾正,
將 Cat.prototype 對象的 constructor 值改為 Cat 。這就是第二行的意思。

 

總結JS物件導向

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.