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运行

 

posted @   漫漫长路</>  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示