简体   繁体   English

单击使用string.prototype

[英]Using string.prototype with click

I'm trying to create an extension method named .Switch() like this: 我正在尝试创建一个名为.Switch()的扩展方法,如下所示:

    String.prototype.Switch = function (p) {
        console.log(this); // should log $obj
    };

    var $obj = $("div");
    $("a", $obj).click(function (e) {
        $obj.Switch(0);
    });

HTML 的HTML

 <div>
   <a href="#">Link</a>
 </div>

And I'm getting an error: Uncaught TypeError: undefined is not a function 我收到一个错误: Uncaught TypeError: undefined is not a function

Can someone show me how this is done? 有人可以告诉我这是怎么做的吗?

$obj is a jQuery object, not a string. $obj是一个jQuery对象,而不是字符串。 If you want to add functions to it, you should do so in this way: 如果要向其添加功能,则应采用以下方式:

jQuery.fn.Switch = function (p) {
     console.log(this); // should log $obj
};

The error your getting is because you are extending the String Object by adding a Switch function to the prototype. 您得到的错误是因为您通过向原型添加Switch函数来扩展String对象。 However, the function your calling Switch on is a JQuery Object. 但是,您调用Switch on的函数是一个JQuery对象。 So If we Modify your example: 因此,如果我们修改您的示例:

String.prototype.Switch = function (p) {
    console.log(p); // should log input
};

var testStr = 'hello'; // create a new instance of String Object

testStr.Switch(5); // will log 5

So similarly if you declare the function on the prototype of the JQuery object you will be able to call that function from all instances of the JQuery Object. 因此,类似地,如果您在JQuery对象的原型上声明函数,则可以从JQuery Object的所有实例中调用该函数。

var $obj = $("div"); is a jQuery object. 是一个jQuery对象。 You could do var $obj = $("div").text(); 你可以做var $obj = $("div").text(); which would call Switch with a string instead of an object. 它将使用字符串而不是对象来调用Switch

You need to do $.prototype.Switch to log the object. 您需要执行$.prototype.Switch来记录该对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM