JavaScript 原型链
// linking prototype objects to build a prototype chain_proto_ vs Object.getPrototypeof(obj) Object.setPrototype0f(obj) //1. obj --> otherProto.prototype --> Object.prototype -->null let otherProto =function(){ this.prop1=456; // 这意味着我们正在创建的对象的实例 this.inner=function(){ console.log("inner method on instance"); } //自动返回对象的实例 } otherProto.prototype.someMethod=function(){ console.log("this is otherProto"); }; let obj=new otherProto(); // console.log(obj.prop1) // obj.inner(); // obj.someMethod(); // obj.toString(); // obj.__proto__.inner();//这个会崩掉 // Object.getPrototypeOf(obj).inner();//失败 // Object.getPrototypeOf(obj).someMethod();//成功 //2. let protoObj={ prop1:456, someMethod:function(){ console.log("this is someMethod"); } }; // let protoObj = new Object(); protoObj.prop1=456; protoObj.someMethod=fnction(){} //Object.getPrototypeOf(protoObj).otherMethod=function(){} protoObj.__proto__.otherMethod=function(){ console.log('this is otherMethod'); }; //3. childObj --> protoObj --> Object.prototype --> null let childObj={}; Object.setPrototypeOf(childObj,protoObj); // console.log(childObj.prop1); // childObj.someMethod(); // childObj.otherMethod(); // childObj.nonmethod();//他不在原型链的任何地方 //4. childObj2 --> protoObj --> Object.prototype --> null let childObj2 = Object.create(protoObj); console.log(childObj2.prop1); // 456 coming from protoObj childObj2.prop1 = 777; // 在 childObj2 中创建了一个名为 prop1 的新属性 console.log(childObj2.prop1,childObj2.__proto__.prop1);// childObj2.someMethod(); //calls the one inside protoObj childObj2.someMethod=function(){ console.log('new method inside childObj2'); } childObj2.someMethod(); childObj2.__proto__.someMethod();
nodejs运行