如何同时创建功能和对象的东西?
假设其名称为obj
在下面的上下文中,它是一个对象:
obj.key1 = "abc";
obj.key2 = "xyz";
在另一个背景下,它是一个像这样的函数:
var test = obj("abc");
如何在JavaScript中创建此对象?
答案 0 :(得分:2)
像这样:
function obj( param ) {
console.log( param );
}
obj.prototype.key1 = "abc";
obj.prototype.key2 = "xyz";
var test = new obj( "abc" );
console.log( test.key1 );
console.log( test.key2 );
键new
需要保存函数上下文。您可以在函数中使用return this
来避免这种情况。
或使用this
代替原型:
function obj( param ) {
console.log( param );
this.key1 = "abc";
this.key2 = "xyz";
}
答案 1 :(得分:2)
function obj( param ){
var that = this;
that.key1 = "default";
that.key2 = "default";
that.someMethod = function(){
return param;
};
that.showMessage = function(){
alert( param );
};
return that;
}
然后:
var test = obj("hi there");
test.key1 = "abc";
test.key2 = "xyz";
test.showMessage();
FIDDLE:http://jsfiddle.net/Xnye5/
或
obj("hi there again").showMessage();
FIDDLE:http://jsfiddle.net/Xnye5/1