码迷,mamicode.com
首页 > Web开发 > 详细

js实现属性只读

时间:2019-05-14 19:21:06      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:地址   code   return   git   规范   vue   没有   set   get   

第一种 Object.defineProperty

这种是在vue源码中看见的

let obj = {
  $data: {}
};

Object.defineProperty(obj, '$data', {
  get() {
    return this;
  },

  set() {
    return console.warn('只读属性不能修改');
  }
})

第二种使用闭包实现

使用场景:团队协作开发的时候,没有详细的文档规范,防止队友误操作。

const Ds = (function () {
  const obj = {
    $data: {
      a:1
    }
  }

  class Ds {
    get() {
      return obj;
    }
  }

  return new Ds();
})()

console.log(Ds.get());
console.log(Ds.obj); // undefind

demo地址: js实现属性只读

js实现属性只读

标签:地址   code   return   git   规范   vue   没有   set   get   

原文地址:https://www.cnblogs.com/meetqy/p/10863688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!