I'm usingconsole.log(value)
however when I use console.log()
If I wanted to play around with stuff and make it do other things is there a way I can create a function like...
var console.log = (function() { // something }
I'm usingconsole.log(value)
however when I use console.log()
If I wanted to play around with stuff and make it do other things is there a way I can create a function like...
var console.log = (function() { // something }
- As far as I know, you can't add a dot in a variable name. var name.log won't work. – Ren Camp Commented Mar 17, 2016 at 11:15
-
2
Dot notation signifies a key in an object, not a normal variable name. So you could do this to overwrite the entire object:
window.console = {};
Or you could do this just to overwrite the function:console.log = function() { /* something */ }
Which is equivalent to this:console["log"] = function() {}
– user162097 Commented Mar 17, 2016 at 11:19
5 Answers
Reset to default 4You could create a wrapper for the console.log
function and then only use your wrapper to write to the console:
function myCustomConsoleLog() {
// do stuff with your arguments
console.log(arguments)
}
Now instead of calling console.log(vars)
you would make a call to myCustomConsoleLog(vars)
.
You don't need to declare console.log
again because it's already declared.
In Javascript, console
is a global variable. There is nothing preventing you from adding, editing or removing properties from it.
So yes, you can just assign a different function to console.log
or whatever else you want:
console.log = function(foo, bar) { ... }
console.anotherProperty = { ... }
If however, you were trying to create a foo.bar
variable that does not exist yet, you could do it in many different ways:
// first approach
var foo;
foo.bar = function() { ... };
// second approach
var foo = {
bar: function() { ... };
};
// third approach
var fnBar = function() { ... };
var foo = { bar: fnBar };
See more at Console API docs and Working with objects.
This is not possible the way you are trying.
What you can do is create an object and add to it some objects:
var obj = {}; // we create an object where we will add the functions
obj.i = 4; // a value
obj.log = function() { }; // a function
you can do the same, like:
var console = {log:function(){ }};
I guess you could do something like this:
var console = {}
console.log = "alert me!"
alert(console.log);
Is that what you meant?