我试图创建一个使用闭包来复制对象的函数。
访问私有函数中的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()); }
;}
答案 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
上使用set
和fullName
方法。