zoukankan      html  css  js  c++  java
  • 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的属性被屏蔽

    附一张经典图:

  • 相关阅读:
    自动化运维工具Ansible实战Playbooks剧本使用
    Mysql5.6.x版本半同步主从复制的开启方法
    mysql数据库的一些基本概念
    mysql之视图
    mysql之索引
    机器学习笔记09-----决策树与随机森林1---决策树概述
    机器学习笔记08-----回归2
    Anaconda 利用conda安装第3方包
    机器学习笔记07-----回归1
    使用navicat导出数据库字典
  • 原文地址:https://www.cnblogs.com/holoyong/p/8999947.html
Copyright © 2011-2022 走看看