如何创建这样的自定义jQuery

时间:2013-01-08 10:58:44

标签: javascript jquery html jquery-plugins

我想要什么

我想创建一个函数在我的控制台中记录一个字符串。以下只是展示我想要的一个例子。

var helloWorld = 'Hello World';
helloWorld.log();

function log(string)
{
   console.log(string);
}

helloWorld.log();部分没有按预期工作但我希望这样做但我不知道如何。

我尝试了什么

Looking at this example

1

(function($) {
  $.fn.log= function() {
    console.log($(this));
  };
})(jQuery);

2

var log = function() {
    console.log($(this));
}

3

jQuery.fn.log = function(){
    console.log($(this));
}

让我发疯的错误

  

TypeError:helloWorld.log不是函数

3 个答案:

答案 0 :(得分:6)

如果要在hello world变量(String)上打印它,可以使用原型函数为字符串提供日志方法。

E.g。像这样:

String.prototype.log= function() {
    console.log(this.toString());
});

然后当你致电helloWorld.log()时,它应该调用此函数。

答案 1 :(得分:3)

为了能够"Hello World".log(),您必须扩展本机String对象,例如:

String.prototype.log = function() { console.log(this); }

要使用log代替console.log,您需要这样的内容:

window.log = (window.console && window.console.log && window.console.log.bind) ?
    console.log.bind(console) : 
    function (e) {alert(JSON.stringify(e)); };

答案 2 :(得分:0)

helloWorld.log();更改为log(helloWorld);

这可能会有所帮助

相关问题