【问题标题】:Create function/object in javascript在javascript中创建函数/对象
【发布时间】:2013-08-01 11:09:54
【问题描述】:

我怎样才能创建一个同时是 functionobject 的东西?
假设它的名字是obj
在以下上下文中,它是一个对象:

obj.key1 = "abc";
obj.key2 = "xyz";

在另一种情况下,它是这样的函数:

var test = obj("abc");

如何在 JavaScript 中创建这个对象?

【问题讨论】:

标签: javascript function object


【解决方案1】:
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();

小提琴:http://jsfiddle.net/Xnye5/

obj("hi there again").showMessage();

小提琴:http://jsfiddle.net/Xnye5/1

【讨论】:

  • 感谢您的回复,您能告诉我如何实现obj("hi there").showMessage() / firebug 给我错误:obj 不是函数
  • 不不,我想在这个约定中使用这个方法:obj("hi there").showMessage()
  • 我想使用我的对象,比如jQuery object
  • @ABFORCE 您不能以这种方式使用它,因为 obj("hi there") 将返回此函数返回的内容(或未定义,如果它不返回任何内容)并且返回的值没有 @ 987654329@方法。
【解决方案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";
 }

【讨论】:

  • var obj = function(param) {....},这样人们就知道有多种选择,以防他需要多个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多