js-Object.create 行为委托设计模式

let obj1 = {
  a: 1,
  init: function(a){
    this.a = a
  },
  getA: function() {
    return this.a
  }
}
let obj2 = Object.create(obj1, {
  c: {value: 'im cc'},
  [Symbol.age]: {value: 33, writable: true},
  age: {
    enumberable: true,
    configurable: true,
    get: function(){ // get 和 set 不能与 writable 和 value 同用
      return this['Symbol.age']
    },
    set: function(age) {
      this['Symbol.age'] = age
    }
  }
})

/* 
  Object.create(复制的对象,额外的属性)
  eg.
  Object.create(a, {
    _age: {
      value: 'xxx',
      writable: true // 所以这里得显示设置为true
    },
    age: {
      value: 'xxx', // 可选,value或者get/set组合
      writable: true, // 可选, 默认为false
      enumberable: true, // 可选
      configurable: true, // 可选
      get: function(){
        return this._age
      },
      set: function(age) {
        this._age = age
      }
    }
  })
*/

// console.log(obj2.__proto__ === obj1)
// Object.create做了下面的事情
// 1. obj2.__proto__ === obj1
// 2. obj2.prototype === undefined
// 3. obj2.constructor === Object -> Function.prototype -> Object.prototype -> null
// 也就是说obj2只有__proto__,没有prototype,构造函数是Object。

// Object.create大概实现:
/* 
  Object.create = function(obj) {
    let F = {}
    F.prototype = obj
    return new F() // 返回一个新对象
  }
*/

obj2.setup = function(a, b){
  console.log('init')
  this.init(a) // 委托调用,初始化其他对象的值
  this.b = b // 初始化自己内部的值
}
obj2.sum = function() { // 定义自己的函数
  return this.a + this.b
}
obj2.setup(2, 8)
console.log(obj2.a)
console.log(obj2.sum())
console.log(obj2.c)
obj2.age = 99
console.log(obj2.age)
// 属性会继承,但值不会同步
console.log(obj1.a) // 1
console.log(obj2.a) // 100

简洁好用,易懂。委托者需要自己实现接口时,通过this便可以调用其他对象的函数,从而实现重写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值