在Javascript中,我们经常需要使用类一样的function
对象。类类的function
对象通常需要公共成员而不是参数,但从长远来看,这似乎过于劳动密集型:
function MyClassLikeFunction(params) {
this.width = (params.width === undefined) ? 50 : params.width;
this.height = (params.height === undefined) ? 50 : params.height;
this.name = (params.name === undefined) ? "foobar" : params.name;
//And a lot of these initializations and some function definitions
}
我打算这样定义:
function MyClassLikeFunction(params) {
//something to enable the behavior
this.initialize("width", 50);
this.initialize("height", 50);
this.initialize("name", "foobar");
//And a lot of these initializations and some function definitions
}
我怎样才能做到这一点?
您可以使用Object.assign
:
function MyConstructor(params) {
Object.assign(this, {
// defaults:
width: 50,
height: 50,
name: 'foobar'
}, params);
}
var obj = new MyConstructor( {width: 100, height: 51} );
console.log(obj);
这可以用于私有变量吗?
是的,就像这样(解构赋值):
var {height, width, name} = Object.assign({
width: 50,
height: 50,
name: 'foobar'
}, params);
console.log(height);
让我们考虑这个原型:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
可以定义原型的public或private成员。例子:
function MyPrototype(params) {
Initializable.call(this, params);
this.initialize("width", 50);
this.initialize("height", 50);
this.initialize("name", "foobar");
//And a lot of these initializations and some function definitions
}