zoukankan      html  css  js  c++  java
  • 关于 Object.create 的笔记

    Object.create方法会返回一个新对象(带有指定的原型对象和属性)
     

    1. 基于一个对象去创建新的对象

     1 var person = {
     2   isHuman: false,
     3   print: function() {
     4     console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
     5   },
     6 };
     7 
     8 const me = Object.create(person);
     9 
    10 // 'name'是 me 的自有属性(非person对象的)
    11 me.name = 'John';
    12 // 继承自person上的isHuman属性将被改写
    13 me.isHuman = true;
    14 
    15 me.print();

    2. 实现继承

     1 // 父类 - Shape
     2 function Shape() {
     3   this.x = 0;
     4   this.y = 0;
     5 }
     6 
     7 Shape.prototype.move = function(x, y) {
     8   this.x += x;
     9   this.y += y;
    10 };
    11 
    12 // 子类 - Rectangle
    13 function Rectangle() {
    14   Shape.call(this);
    15 }
    16 
    17 // 继承
    18 Rectangle.prototype = Object.create(Shape.prototype);
    19 Rectangle.prototype.constructor = Rectangle;
    20 
    21 var rect = new Rectangle();

    3. 方法使用细节

     1 var o;
     2 // 创建一个原型为null的空对象
     3 o = Object.create(null);
     4 
     5 // 以字面量创建的空对象 o = {} 相当于:
     6 o = Object.create(Object.prototype);
     7 
     8 // 关于Object.create的 propertyObject 参数的使用
     9 o = Object.create(Object.prototype, {
    10   // 添加数据属性
    11   foo: {
    12     writable: true,
    13     configurable: true,
    14     value: 'hello',
    15   },
    16   // 添加存取器属性
    17   bar: {
    18     configurable: false,
    19     get: function() {
    20       return 10;
    21     },
    22     set: function(val) {
    23       console.log('Set "o.bar" to ', val);
    24     },
    25   },
    26 });
    27 
    28 // function Cons() {} 
    29 // var c = new Cons();
    30 // // 等同于:
    31 // var o = Object.create(Cons.prototype);
  • 相关阅读:
    Node.js 究竟是什么?
    天津自考学习之“六步看书法”
    C专家编程cdecl
    Linux系统启动流程及安装命令行版本
    Java学习路线
    GCC内置宏
    GMP
    二级存储构建倒排索引
    余弦距离与欧式距离
    af
  • 原文地址:https://www.cnblogs.com/fanqshun/p/15624123.html
Copyright © 2011-2022 走看看