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方法
相关文章
相关标签/搜索