求教覆盖原型时, firstPrisoner._proto_.sentence中为啥不能使用_proto_属性手动的在原型链上‘’往上爬‘
发布于 9 年前 作者 SweetHeartXi 3825 次浏览 最后一次编辑是 8 年前 来自 问答

//囚犯示例 //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终端输出: console.log( firstPrisoner.proto.sentence ); ^ TypeError: Cannot read property ‘sentence’ of undefined at Object.<anonymous> (/home/xxh/workspace/t6.js:42:35) at Module._compile (module.js:460:26) at Object.Module._extensions…js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3

回到顶部