javascript - 将变量传递给原型(prototype) Javascript

标签 javascript html

我想将选择器值发送到原型(prototype)。目前我正在使用

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;
    }
};

显示未定义。

有没有办法传递变量?

最佳答案

不,您无法从原型(prototype)方法访问它。 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;
};

关于javascript - 将变量传递给原型(prototype) Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17027093/

相关文章:

javascript - 检查数组是否包含不同的值

javascript - 在 for 循环中使用 jQuery.each 将数组映射到元素文本?

html - 滚动时如何使页面的一部分固定在顶部

html - 移动导航栏的下拉菜单溢出

javascript - 使用鼠标悬停更改类的 innerHTML

javascript - Bootstrap v3 的 btn-xs 类不适用于 iphone

javascript - Angular Directive(指令) ngModel 在模糊时发生变化

JavaScript。从工作正则表达式创建正则表达式对象时出现问题

javascript - AngularJS $LogProvider 抛出非法访问错误

javascript - jQuery .nextAll() 不适用于 html 表列