淺談JavaScript 覆蓋原型以及更改原型
更新時間:2016年08月31日 09:07:53 投稿:jingxian
下面小編就為大家?guī)硪黄獪\談JavaScript 覆蓋原型以及更改原型。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨過來看看吧
覆蓋原型
//囚犯示例
//1.定義原型對象
var proto = {
sentence : 4, //監(jiān)禁年限
probation: 2 //緩刑年限
};
//2.定義原型對象的構(gòu)造函數(shù)
var Prisoner = function(name, id) {
this.name = name;
this.id = id;
};
//3.將構(gòu)造函數(shù)關聯(lián)到原型
Prisoner.prototype = proto;
//4.實例化對象——采用工廠函數(shù)實例化對象
var makePrisoner = function(name, id) {
//采用工廠函數(shù)實力化對象prisoner
var prisoner = Object.create( proto );
prisoner.name = name;
prisoner.id = id;
return prisoner;
};
var firstPrisoner = makePrisoner( 'Joe', '12A' );
//firstPrisoner.sentence在firstPrisoner對象找不到sentence屬性,
//所以查找對象的原型并找到了Both of these output 4
console.log( firstPrisoner.sentence );
console.log( firstPrisoner.__proto__.sentence );
//把對象的sentence屬性設置為10
firstPrisoner.sentence = 10;
//outputs 10
//確定對象上的屬性值已設置為10
console.log( firstPrisoner.sentence );
//但是對象的原型并沒有變化,值仍然為4
console.log( firstPrisoner.__proto__.sentence );
//為了使獲取到的屬性回到原型的值,將屬性從對象上刪除
delete firstPrisoner.sentence;
//接下來,JavaScript引擎在對象上不能再找到該屬性,
//必須回頭去查找原型鏈,并在原型對象上找到該屬性
// Both of these output 4
console.log( firstPrisoner.sentence );
console.log( firstPrisoner.__proto__.sentence );
ubuntu 終端node輸出
xxh@xxh-E440:~/workspace$ node t6 4 4 10 4 4 4
那么如果改變了原型對象的屬性值,會發(fā)生什么呢?我知道你在思考。
以上這篇淺談JavaScript 覆蓋原型以及更改原型就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
js面向?qū)ο笾o態(tài)方法和靜態(tài)屬性實例分析
這篇文章主要介紹了js面向?qū)ο笾o態(tài)方法和靜態(tài)屬性,實例分析了靜態(tài)方法和靜態(tài)屬性的原理及應用,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01
JS組件Bootstrap實現(xiàn)彈出框和提示框效果代碼
這篇文章主要介紹了JS組件Bootstrap實現(xiàn)彈出框和提示框效果代碼,對彈出框和提示框感興趣的小伙伴們可以參考一下2015-12-12

