关于vue中this.attr代替this.data.attr访问的原理

请看如下例子:

  

    var obj = {
        name:"zhuwei",
        age:18
      }
      function Person(data){
        this.data = data;
      }
      var person = new Person(obj);
      console.log(person.data.age)//18
      console.log(person.age)//undefined

第一个输出的是18,第二个输出的是undefined,那现在我们希望第二个也是输出18,那应该如何实现呢,

我们可以通过Object.defineProperty给Person对象定义属性,举个例子,现在data对象里面有name和age两个属性,我们就给Person对象定义name和age属性,然后在他们的get和set访问器里面做一些手脚:

    var obj = {
        name:"zhuwei",
        age:18
      }
      function Person(data){
        this.data = data;
        var self = this;
        console.log(Object.keys(data));
        Object.keys(data).forEach(function(key){
          self.profx(key);
        });
      }
      Person.prototype.profx = function(key){
        var self = this;
        Object.defineProperty(this,key,{
          get:function(){
            return self.data[key];
          },
          set:function(newValue){
            self.data[key] = newValue;
          }
        })
      }
      var person = new Person(obj);
      console.log(person.data.age)//18
      console.log(person.age)//18

  

posted @ 2018-02-22 10:09  dami.white  阅读(946)  评论(0编辑  收藏  举报