我想将选择器值发送到原型。目前我正在使用
var selector; //id of html element
function $(selector)
{
if(window===this)
return new $(selector);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};
显示未定义。
有没有办法传递变量?
答案 0 :(得分:3)
不,您无法从原型方法访问它。 selector
参数是构造函数的局部变量。
但是,您可以将其作为实例的属性提供:
function $(selector) {
if(!(this instanceof $))
return new $(selector);
this.selector = selector; // assigns the variable to a property
}
$.prototype.tooltip = function(){
console.log(this.selector); // access the property on the instance
//do calculations with the selector value
return this;
};
答案 1 :(得分:1)
我看不到您在哪里调用任何功能或设置selector
。但是,一个问题是您的selector
定义中的形式函数参数$
会屏蔽外部变量selector
。如果你消除了函数参数,它应该更好(假设你也在某处设置selector
):
var selector; //id of html element
function $()
{
if(window===this)
return new $(selector);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};
现在编写代码的方式,就像它编写如下:
var selector; //id of html element
function $(x)
{
if(window===this)
return new $(x);
return this;
}
$.prototype={
tooltip: function(){
console.log(selector);
//do calculations with the selector value
return this;
}
};