我想创建一个函数在我的控制台中记录一个字符串。以下只是展示我想要的一个例子。
var helloWorld = 'Hello World';
helloWorld.log();
function log(string)
{
console.log(string);
}
helloWorld.log();
部分没有按预期工作但我希望这样做但我不知道如何。
(function($) {
$.fn.log= function() {
console.log($(this));
};
})(jQuery);
var log = function() {
console.log($(this));
}
jQuery.fn.log = function(){
console.log($(this));
}
TypeError:helloWorld.log不是函数
答案 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);
。
这可能会有所帮助