覆蓋原型
//囚犯示例 //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ù)關(guān)聯(lián)到原型 Prisoner.prototype = proto; //4.實(shí)例化對象――采用工廠函數(shù)實(shí)例化對象 var makePrisoner = function(name, id) { //采用工廠函數(shù)實(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屬性設(shè)置為10 firstPrisoner.sentence = 10; //outputs 10 //確定對象上的屬性值已設(shè)置為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)容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答