2011-11-25 109 views
0

我有我打电话以下方式功能,但它返回someVariable.clean is not a functionJavaScript构造函数返回错误

下面是代码:

var someVariable = function() { 
     this.clean = function(obj) { 
      alert(obj); 
     } 
    } 

    someVariable.clean('test'); //call 

任何想法,为什么它正在发生什么我做错了吗?

回答

1

如果your're不是在ES5严格模式下,你将添加功能.clean()全局对象。

所以,只需拨打clean('test');就可以在这里工作。如果你想像你描述的那样,你需要返回一个对象的函数。

var someVariable = function() { 
    return { 
     clean: function(obj) { 
      alert(obj); 
     } 
    }; 
}; 

如果你在ES5严格模式下,这个代码将抛出一个错误,因为this将被绑定到null。什么this context variable被引用,总是取决于如何调用该函数。在你的情况下,如上所述,thiswindownull

这也将工作,如果你愿意与new键盘调用你的函数:

new someVariable().clean('test'); 

这是因为,new使得构造函数this总是被绑定到新创建的功能函数内的对象。

0

它不是函数的属性。只有在执行该函数时才会设置,然后将其添加到全局对象(这仍不是您想要的)。

而应该将它设置相同的方式,你怎么称呼它:

var someVariable = function() { 
    // ... 
} 

someVariable.clean = function(obj) { 
    alert(obj); 
} 

someVariable.clean('test'); // call 
1

发生这种情况的原因是this在功能范围内仍然为window(就像您在顶层声明clean函数那样)。你想要的是:

var someVariable = function() {}; 
someVariable.clean = function(obj) { 
    alert(obj); 
} 

someVariable.clean('test'); //call 
1

你已经忘记了。如果你想静态类的香味,然后考虑用文字来初始化原型

new someVariable().clean('test'); 

someVariable = { 
    clean: function(obj) { 
      alert(obj); 
     } 
}; 

现在你可以拨打你的方式:

someVariable.clean('test'); 
+0

谢谢,这是非常教育!从来没有听说过EC5模式。 – devjs11

0

尽量做到这一点,以更好地接近并解决您的错误。

var someVariable = cleanfunction(id); 

function cleanfunction(id) 
{   
    clean: function(id) { 
     alert(id);   
    }   
}