JavaScript用于复制对象的对象

时间:2017-05-25 08:46:03

标签: javascript

参与Javascript课程,我一直试图弄清楚如何回答/理解如何完成这个问题,想知道是否有人可以提供帮助。

 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()); }

     ;}

2 个答案:

答案 0 :(得分:0)

var Person = function(person){
    var name = 'John Doe';
    function copy(){
        var newPerson = Object.assign({}, person);
        Object.defineProperty(newPerson, 'name', {
            get: function() { return name; },
            set: function(newName){ if(typeof newName !== 'string') {console.error('invalid name')} else name = newName},
            enumerable: true,
            configurable: true
        });
        return newPerson;
    }
    return copy();
};

var person1 = {
    age: 20,
    location: 'India'
}
var person2 = Person(person1);
var person3 = Person(person1);
person3.name = 1234;        // invalid name
person3.name = 'Mr. India';
console.log(person1.name);  // undefined
console.log(person2.name);  // John Doe
console.log(person3.name);  // Mr. India

答案 1 :(得分:0)

使用Object.assign复制普通属性,然后在以下情况下手动复制特殊属性:

copy = Object.assign({}, original);
copy.year = original.year;

但是这并没有在任何地方使用闭包,所以我不确定它是否是你的教程所寻找的。