使用闭包的JS复制仅通过get / accessor方法可用的私有set对象

时间:2017-05-26 17:13:30

标签: javascript

我试图创建一个使用闭包来复制对象的函数。

访问私有函数中的getter属性。

 function Container(param) {
      var person = {
      firstName: 'Jimmy',
      lastName: 'Smith',
      get fullName() {
      return this.firstName + ' ' + this.lastName;
      },
    set fullName (name) {
       var words = name.toString().split(' ');
       this.firstName = words[0] || '';
       this.lastName = words[1] || '';
   }
  }
 }

  // Attempting to clone private getter don't know how to access it.

     function objectClone(person) {

       var orginal = person //Trying to access the private method

       var clone = function cloneObj { Object.assign({}, original); }

       clone.prototype.spillSecret = function() { alert(this.getfullName()); }

     ;}

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试创建Container的新实例。首先,我们应该修复该代码:

function Container(param) {
  this.firstName = 'Jimmy';
  this.lastName = 'Smith';
  Object.defineProperty(this, 'fullName', {
    get: function() {
      return this.firstName + ' ' + this.lastName;
    },
    set: function(name) {
      var words = name.toString().split(' ');
      this.firstName = words[0] || '';
      this.lastName = words[1] || '';
    }
  });
}

现在,要创建新的Container对象,我们使用new

var person = new Container();

person会在get上使用setfullName方法。