覆蓋原型
//囚犯示例
//1.定義原型對象
var proto = {
sentence : 4, //監禁年限
probation: 2 //緩刑年限
};
//2.定義原型對象的構造函數
var Prisoner = function(name, id) {
this.name = name;
this.id = id;
};
//3.將構造函數關聯到原型
Prisoner.prototype = proto;
//4.實例化對象——采用工廠函數實例化對象
var makePrisoner = function(name, id) {
//采用工廠函數實力化對象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
那麼如果改變了原型對象的屬性值,會發生什麼呢?我知道你在思考。
以上這篇淺談JavaScript 覆蓋原型以及更改原型就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。