• JS简记-对象关联


    js的继承就是通过关联对象实现的,使用Object.prototype.isPrototypeOf()和instanceof可以判断一个对象是否在另一个对象关联链(__proto__链)上。

    1 var o = {};
    2 console.log(o instanceof Object);//true
    3 console.log(Object.prototype.isPrototypeOf(o));//true
    4 //注意,isPrototypeOf是Object.prototype对象的函数,这就意味着通常情况下,只有继承(关联)Object才能使用该函数。
    5 o = Object.create(null);
    6 console.log(o.isPrototypeOf(Object.prototype));//TypeError,isPrototypeOf为undefined,对undefined进行函数调用,自然是TypeError,这时就只能通过instanceof判断了。

    当然也可以复制Object.prototype.isPrototypeOf

    1 o = Object.create(null);
    2 var proto = Object.create(null, {
    3     isPrototypeOf:{
    4         value: Object.prototype.isPrototypeOf
    5     }
    6 })
    7 Object.setPrototypeOf(o, proto);//注意,由于没有继承Object.prototype中__proto__的setter/getter,所以这里不能使用o.__proto__ = proto;
    8 console.log(proto.isPrototypeOf(o));

    for in会遍历对象本身及其__proto__链上的所有enumerable属性,而Object.keys只会涉及对象自身的enumerable属性。

    __proto__链会带来“父类”属性屏蔽:

     1 var son = Object.create(null);
     2 var parent= Object.create(null, {
     3     eye: {
     4         value: "blue",
     5         writable: true//使用普通字面量声明属性时,writable、enumerable、configurable默认均为true
     6     },
     7     age: {
     8         value: 30,
     9         writable: true
    10     }    
    11 });
    12 Object.setPrototypeOf(son, parent);
    13 son.eye = "black";
    14 console.log(son.eye);//black
    15 console.log(Object.getPrototypeOf(son).eye);//blue,parent的属性被屏蔽
    16 son.age++
    17 console.log(son.age);//31
    18 console.log(Object.getPrototypeOf(son).age);//30,age++相当于age=age+1,parent的属性被屏蔽

    附一张经典图:

  • 相关阅读:
    gethostbyname() 用域名或主机名获取IP地址
    recv, recvfrom, recvmsg 从套接口接收一个消息
    献给初学者:谈谈如何学习Linux操作系统
    Linux 文件处理 之扫描目录 DIR
    Python 使用sys模块
    struct dirent和DIR结构体
    职场人必读的文字只花10分钟影响你一辈子!
    信号量与线程互斥锁的区别
    send/sendto/sendmsg函数解析
    互联网常见Open API文档资源
  • 原文地址:https://www.cnblogs.com/holoyong/p/8999947.html
Copyright © 2020-2023  润新知