最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Is it possible to add a dot in a variable name in Javascript? - Stack Overflow

programmeradmin3浏览0评论

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 }

Share Improve this question asked Mar 17, 2016 at 11:13 pourmesomecodepourmesomecode 4,36812 gold badges53 silver badges91 bronze badges 2
  • 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
Add a ment  | 

5 Answers 5

Reset to default 4

You 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?

发布评论

评论列表(0)

  1. 暂无评论