0

I would am working on an app that's written in JavaScript. I'd like to extend that Console object. Is there a way do that? Currently, I have:

Console.prototype.execute = function() {
  console.log('execute this...');
}

Then, in my code, I have:

console.execute();

When I run my page, I see the following in the console window:

Console is not defined

This implies I can't extend Console. What am I doing wrong?

4
  • 1
    The console API is not standardized. How to do it and if it's possible at all likely depends on the environment the code runs in. If console is extensible, you could just do console.execute = ...;. Commented Dec 27, 2016 at 19:19
  • 3
    Just use console.execute = function(){};. Commented Dec 27, 2016 at 19:20
  • Adding it to the console object itself makes even more sense when you think it's a singleton Commented Dec 27, 2016 at 19:26
  • 1
    In what environment are you? In node, there's a Console module which you could (but shouldn't) extend. Commented Dec 27, 2016 at 19:32

1 Answer 1

1

There is not a Console function that maps to the console object. You can check it using:

console.constructor.
  => function Object() { [native code] }

or

Object.getPrototypeOf(console) 
  => Object {}

It is just an object.
Just add your functions to the console object:

console.execute = function() {
   console.log('execute this...');
}
Sign up to request clarification or add additional context in comments.

2 Comments

That depends on the browser, actually.
@Bergi- this correct, but Chrome and Firefox (both take 85% of the market share) don't implement it using prototype so it is basically irrelevant to implement it like this, anyway you probably won't be able to instantiate a new Console type in the browsers that support the feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.