JavaScript构造函数返回错误
问题描述:
我有我打电话以下方式功能,但它返回someVariable.clean is not a function
JavaScript构造函数返回错误
下面是代码:
var someVariable = function() {
this.clean = function(obj) {
alert(obj);
}
}
someVariable.clean('test'); //call
任何想法,为什么它正在发生什么我做错了吗?
答
如果your're不是在ES5严格模式下,你将添加功能.clean()
全局对象。
所以,只需拨打clean('test');
就可以在这里工作。如果你想像你描述的那样,你需要返回一个对象的函数。
var someVariable = function() {
return {
clean: function(obj) {
alert(obj);
}
};
};
如果你在ES5严格模式下,这个代码将抛出一个错误,因为this
将被绑定到null
。什么this context variable
被引用,总是取决于如何调用该函数。在你的情况下,如上所述,this
是window
或null
。
这也将工作,如果你愿意与new
键盘调用你的函数:
new someVariable().clean('test');
这是因为,new
使得构造函数和this
总是被绑定到新创建的功能函数内的对象。
答
它不是函数的属性。只有在执行该函数时才会设置,然后将其添加到全局对象(这仍不是您想要的)。
而应该将它设置相同的方式,你怎么称呼它:
var someVariable = function() {
// ...
}
someVariable.clean = function(obj) {
alert(obj);
}
someVariable.clean('test'); // call
答
发生这种情况的原因是this
在功能范围内仍然为window
(就像您在顶层声明clean
函数那样)。你想要的是:
var someVariable = function() {};
someVariable.clean = function(obj) {
alert(obj);
}
someVariable.clean('test'); //call
答
你已经忘记了。如果你想静态类的香味,然后考虑用文字来初始化原型类
new someVariable().clean('test');
:
someVariable = {
clean: function(obj) {
alert(obj);
}
};
现在你可以拨打你的方式:
someVariable.clean('test');
答
尽量做到这一点,以更好地接近并解决您的错误。
var someVariable = cleanfunction(id);
function cleanfunction(id)
{
clean: function(id) {
alert(id);
}
}
谢谢,这是非常教育!从来没有听说过EC5模式。 – devjs11