在JavaScript中缩写console.log [英] Abbreviating console.log in JavaScript
问题描述
可能重复:
chrome console.log的别名
这真是太傻了,但我不能缩写console.log(我正在使用Chrome)。这是我天真的尝试:
This is really silly, but I can't abbreviate console.log (I'm using Chrome). Here's my naive attempt:
var log = console.log;
log("Bingo"); // Uncaught TypeError: Illegal invocation
我应该使用apply()吗?但是我必须传递参数,对吗?
Should I be using apply()? But then I'd have to pass along the arguments, right?
推荐答案
这失败了,因为对Javascript方法的引用不包括引用对象本身。将方法 console.log
分配给变量的简单而正确的方法,并将调用应用于 console
,是在 log
方法上使用 bind
方法,传递 console
作为参数:
This fails because references to Javascript methods do not include a reference to the object itself. A simple and correct way to assign the method console.log
to a variable, and have the call apply to console
, is to use the bind
method on the log
method, passing console
as the argument:
var log = console.log.bind(console);
每个人都有一个隐藏的这个
参数方法,并且由于可以说是糟糕的语言设计,当你获得对方法的引用时它并没有关闭。 bind
方法的目的是为函数预先设置参数,并返回一个函数,该函数接受函数所期望的其余参数。 bind
的第一个参数应该始终是 this
参数,但实际上可以使用它来分配任意数量的参数。
There is a hidden this
argument to every method, and because of arguably bad language design, it's not closured when you get a reference to a method. The bind
method's purpose is to preassign arguments to functions, and return a function that accepts the rest of the arguments the function was expecting. The first argument to bind
should always be the this
argument, but you can actually assign any number of arguments using it.
使用 bind
具有明显的优势,即您不会失去方法接受更多参数的能力。例如, console.log
实际上可以接受任意数量的参数,并且它们将在一个日志行上连接。
Using bind
has the notable advantage that you don't lose the method's ability to accept more arguments. For instance, console.log
can actually accept an arbitrary number of arguments, and they will all be concatenated on a single log line.
以下是使用 bind
预先设置更多参数到 console.log
:
Here is an example of using bind
to preassign more arguments to console.log
:
var debugLog = console.log.bind(console, "DEBUG:");
调用 debugLog
将为日志消息添加前缀 DEBUG:
。
Invoking debugLog
will prefix the log message with DEBUG:
.
这篇关于在JavaScript中缩写console.log的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!