JS的面向對象與原型

 原型函數

const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true }; ⇽--- 建立3個帶有屬性的對象
assert("skulk" in yoshi, "Yoshi can skulk");
assert(!("sneak" in yoshi)), "Yoshi cannot sneak");
assert(!("creep" in yoshi)), "Yoshi cannot creep"); ⇽--- yoshi對象只能訪問自身的屬性skulk
Object.setPrototypeOf(yoshi, hattori); ⇽--- Object. setProto-typeOf方法, 將對象hattori設置爲yoshi對象的原型
assert("sneak" in yoshi, "Yoshi can now sneak"); ⇽--- 經過將hattori對象設置爲yoshi對象的原型, 如今yoshi能夠訪問hattori對象的屬性
assert(!("creep" in hattori)), "Hattori cannot creep"); ⇽--- 目前hattori對象還不具備屬性creep
Object.setPrototypeOf(hattori, kuma); ⇽--- 將kuma對象設置爲hattori對象的原型
assert("creep" in hattori, "Hattori can now creep"); ⇽--- 如今hattori對象能夠訪問屬性creep
assert("creep" in yoshi, "Yoshi can also creep"); ⇽--- 經過將hattori對象設置爲yoshi對象的原型, 如今yoshi對象也能夠訪問屬性creep

 對象構造器與原型this

function Ninja(){} ⇽--- 定義一個空函數, 什麼也不作, 也沒有返回值
Ninja.prototype.swingSword = function(){
return true;
}; ⇽--- 每一個函數都具備內置的原型對象, 咱們能夠對其自由更改
const ninja1 = Ninja();
assert(ninja1 === undefined , "No instance of Ninja created."); ⇽--- 做爲函數調用Ninja, 驗證該函數沒有任何返回值
const ninja2 = new Ninja();
assert(ninja2 && ninja2.swingSword && ninja2.swingSword(),"Instance exists and method is callable." ); ⇽--- 做爲構造函數調用Ninja, 驗證不只建立了新的實例, 而且該實例具備原型上的方法

每一個函數都有一個原型對象, 該原型對象將被自動設置爲經過該函數建立對象的原型。spa

關於實例屬性與原型屬性prototype

function Ninja(){
this.swung = false; ⇽--- 建立布爾類型的實例變量, 並初始化該變量的默認值爲false
this.swingSword = function(){
return !this.swung; ⇽--- 建立實例方法, 該方法的返回值爲實例變量swung取反
};
Ninja.prototype.swingSword
= function(){ return this.swung; }; ⇽--- 定義一個與實例方法同名的原型方法, 將會優先使用哪個呢 const ninja = new Ninja(); assert(ninja.swingSword(),"Called the instance method, not the prototype met};

經過原型一切均可以在運行時進行修改code

function Ninja(){
this.swung = true;
} ⇽--- 定義了一個構造函數, 該構造函數中建立了一個swung屬性, 初始化爲布爾值
const ninja1 = new Ninja(); ⇽--- 經過new操做符調用構造函數, 建立實例Ninja
Ninja.prototype.swingSword = function(){
return this.swung;
}; ⇽--- 在實例對象建立完成以後, 在原型上添加一個方法
assert(ninja1.swingSword(), "Method exists, even out of order."); ⇽--- 驗證該方法存在於對象中
Ninja.prototype
= { pierce: function() { return true; } } ⇽--- 使用字面量對象徹底重寫Ninja的原型對象, 僅有一個pierce方法 assert(ninja1.swingSword(),"Our ninja can still swing!"); ⇽--- 儘管咱們已經徹底替換了Ninja的構造器原型, 可是實例化後的Ninja對象仍然具備swingSword方法, 由於對象ninja1仍然保持着對舊的Ninja原型的引用 const ninja2 = new Ninja(); assert(ninja2.pierce(),"Newly created ninjas can pierce"); assert(!ninja2.swingSword, "But they cannot swing!"); ⇽--- 新建立的ninja2實例擁有新原型的引用, 所以不具備swingSword方法, 僅具備pierce方法
相關文章
相關標籤/搜索