I am trying to mimic the behavior of Java to call the toString() method when we try to print the object using console.log statement or alert.
Currently, I have tried something like
class Some {
constructor(array = []) {
this.pvtData = array;
}
toString = () => JSON.stringify(this.pvtData);
}
const s = new Some([1, 2, 3]);
console.log(s);
The expected output should be
[1,2,3]
But, I am getting the output as
{
"toString": () => JSON.stringify(this.pvtData),
"pvtData": [
1,
2,
3
]
}
Can anyone help me in resolving the issue and getting the desired output?
Note:
I don't want to use console.log(s.toString());. Basically, the console.log statement shouldn't change.
What you're doing will work for alert because alert converts its argument to string, but not for console.log with most consoles, because they don't convert to string, they try to show you a representation of the object.
There is no equivalent method for console.log across environments.¹ If you want that to happen for console.log, you'll have to override it:
const oldLog = console.log.bind(console);
console.log = (...args) => oldLog(...args.map(String));
Live Example:
class Some {
constructor(array = []) {
this.pvtData = array;
}
toString = () => JSON.stringify(this.pvtData);
}
const oldLog = console.log.bind(console);
console.log = (...args) => oldLog(...args.map(String));
const s = new Some([1, 2, 3]);
console.log(s);
Obviously, don't do that in a general-purpose library that other people are going to use. It's fine in your own app or page, though.
Or better yet, just have your own logging function that you use instead that wraps console.log:
// The log function
const log = (...args) => console.log(...args.map(String));
// Usage
class Some {
constructor(array = []) {
this.pvtData = array;
}
toString = () => JSON.stringify(this.pvtData);
}
const s = new Some([1, 2, 3]);
log(s);
¹ In Node.js, the console used to look for a method called inspect, but they stopped doing that a while back.
Side note: There's usually no reason to make toString an arrow function. It works (in an environment that supports the class fields proposal), but it's usually unnecessary. Just make it a method:
class Some {
constructor(array = []) {
this.pvtData = array;
}
toString() {
return JSON.stringify(this.pvtData);
}
}
Related
I have some objects:
var a = {
toString: () => 'a'
}
var b = {
toString: () => 'b'
}
function someFunc(...params) {
params.forEach((p)=>{
console.log(p); //consoles - {toString: ƒ toString()} for both objects
})
}
someFunc(a,b);
I want to pass these objects to some functions like memoize function, isEqual function, deepCopy function etc. I don't want to use any third party library such as lodash. I want to understand how do we differentiate between these objects inside someFunc?
I have tried : JSON.parse(JSON.stringify()) but this doesn't work in case of objects having functions.
Codesandbox
Edit:
I have tried Implementing the object refrence method.
function someFunc() {
let cache = {};
return function (...params) {
var ObjectReference = [];
let set = {};
params.forEach((p) => {
ObjectReference.push(p);
set["ObjectReference." + ObjectReference.indexOf(p)+p] = true;
});
let key = JSON.parse(JSON.stringify(set))
console.log(key);
if (cache[key]) {
console.log("cached");
} else {
cache[key] = true;
console.log("Not cached");
}
};
}
mem(a, b); //not cached
mem(b, a); //cached - should be **not cached**
console.log(key); gives:
{ObjectReference.0a: true, ObjectReference.1b: true}
{ObjectReference.0b: true, ObjectReference.1a: true}
As we can see the two objects are different. I'm unable to understand why it goes inside cached block?
Edit 2 : The above is happening because the key is getting set as [object object]. To avoid this I tried using Map and WeakMap but they are failing for
mem(a, b); //not cached
mem(a, b); // not cached
Probably my misunderstanding of Testdouble, but I've created this example to illustrate the issue I'm having:
const test = require("ava");
const td = require("testdouble");
const reducer = async (state, event) => {
if (event.id === "123") {
const existing = await state.foo("", event.id);
console.log("existing:", existing);
}
};
test("foo", async (t) => {
const foo = td.func(".foo");
const state = td.object({
foo
});
td.when(foo(td.matchers.anything(), td.matchers.anything())).thenResolve({
id: "123"
});
await reducer(state, {
id: "123",
nickname: "foo"
});
});
This logs: existing: undefined
Whereas I believe it should log: existing: { id: "123" } as stated by the td.when()
What am I missing?
I think your issue is that td.object doesn't work the way you think it does:
td.object(realObject) - returns a deep imitation of the passed object, where each function is replaced with a test double function named for the property path (e.g. If realObject.invoices.send() was a function, the returned object would have property invoices.send set to a test double named '.invoices.send')
Source: https://github.com/testdouble/testdouble.js#tdobject
So when you do…
const foo = td.func();
const obj = td.object({foo});
… you're actually mocking foo twice.
Here's a demo:
const td = require('testdouble');
const num2str = td.func('num->string');
td.when(num2str(42)).thenReturn('forty two');
td.when(num2str(43)).thenReturn('forty three');
td.when(num2str(44)).thenReturn('forty four');
const x = {num2str};
const y = td.object({num2str});
num2str(42);
x.num2str(43);
y.num2str(44);
Then we can inspect x.num2str and we can see that it is the same test double as num2str:
td.explain(x.num2str).description;
/*
This test double `num->string` has 3 stubbings and 2 invocations.
Stubbings:
- when called with `(42)`, then return `"forty two"`.
- when called with `(43)`, then return `"forty three"`.
- when called with `(44)`, then return `"forty four"`.
Invocations:
- called with `(42)`.
- called with `(43)`.
*/
However y.num2str is a completely different test double:
td.explain(y.num2str).description;
/*
This test double `.num2str` has 0 stubbings and 1 invocations.
Invocations:
- called with `(44)`.
*/
I think what you're looking for is the "property replacement" behaviour of td.replace:
const z = {
str2num: str => parseInt(str),
num2str: num => {
throw new Error('42!');
}
};
td.replace(z, 'num2str');
td.when(z.num2str(42)).thenReturn('FORTY TWO!!');
The z.str2num function hasn't been mocked:
z.str2num("42");
//=> 42
However z.num2str is a fully-fledged test double:
z.num2str(42);
//=> 'FORTY TWO!!'
td.explain(z.num2str).description;
/*
This test double `num2str` has 1 stubbings and 1 invocations.
Stubbings:
- when called with `(42)`, then return `"FORTY TWO!!"`.
Invocations:
- called with `(42)`.
*/
I think there is something that i'm missing about method chaining. To me it feels incomplete.
Method chaining works by having each method return this so that another method on that object can be called. However, the fact that the return value is this and not the result of the function seems inconvenient to me.
Here is a simple example.
const Obj = {
result: 0,
addNumber: function (a, b) {
this.result = a + b;
return this;
},
multiplyNumber: function (a) {
this.result = this.result * a;
return this;
},
}
const operation = Obj.addNumber(10, 20).multiplyNumber(10).result
console.log(operation)
key points:
Every method in the chain Obj.addNumber(10, 20).multiplyNumber(10) returns this.
The last part of the chain .result is the one that returns a value other than this.
The problem with this approach is that it require you to tack on a property / method to get a value at the end other thanthis.
Compare this with built-in functions in JavaScript.
const str = " SomE RandoM StRIng "
console.log(str.toUpperCase()) // " SOME RANDOM STRING "
console.log(str.toUpperCase().trim()) // "SOME RANDOM STRING"
console.log(str.toUpperCase().trim().length) // 18
key points:
Each function in the chain returns the result of the function not this (maybe this is done under the hood)
No property / method is required at the end of the chain just to get the result.
Can we implement method chaining to behave the way built-in functions in Javascript behave?
First of all, each of your console.log doesn't return properly:
console.log(str.toUpperCase.trim) //undefined
It returns undefined because str.toUpperCase returns the function object and does not execute the function itself so it won't work
The only correct usage is
console.log(str.toUpperCase().trim()
Now about your question, it is pretty easy to do it without a result and it is much more efficient.
Everything in javascript has a method called valueOf(), here is my example of calling everything like that for numbers, though I prefer just making functions instead of Objects.
const Obj = {
addNumber: function (a = 0) {
return a + this.valueOf();
},
multiplyNumber: function (a = 1) {
return a*this.valueOf();
},
}
const nr = 2;
Object.keys(Obj).forEach(method => {
Number.prototype[method] = Obj[method];
})
console.log(Number.prototype); // will print out addNumber and multiplyNumber
// Now You can call it like this
console.log(nr.addNumber().multiplyNumber()); // Prints out 2 because it becomes (nr+0)*1
console.log(nr.addNumber(3).multiplyNumber(2)) // Prints out 10;
I think you are misunderstanding what method chaining actually is. It is simply a shorthand for invoking multiple methods without storing each intermediate result in a variable. In other words, it is a way of expressing this:
const uppercase = " bob ".toUpperCase()
const trimmed = uppercase.trim()
as this
const result = " bob ".toUpperCase().trim()
Nothing special is happening. The trim method is simply being called on the result of " bob ".toUpperCase(). Fundamentally, this boils down to operator precedence and the order of operations. The . operator is an accessor, and is evaluated from left to right. This makes the above expression equivalent to this (parens used to show order of evaluation):
const result = (" bob ".toUpperCase()).trim()
This happens regardless of what is returned by each individual method. For instance, I could do something like this:
const result = " bob ".trim().split().map((v,i) => i)
Which is equivalent to
const trimmed = " bob ".trim()
const array = trimmed.split() //Note that we now have an array
const indexes = array.map((v,i) => i) //and can call array methods
So, back to your example. You have an object. That object has encapsulated a value internally, and adds methods to the object for manipulating the results. In order for those methods to be useful, you need to keep returning an object that has those methods available. The simplest mechanism is to return this. It also may be the most appropriate way to do this, if you actually are trying to make the object mutable. However, if immutability is an option, you can instead instantiate new objects to return, each of which have the methods you want in the prototype. An example would be:
function MyType(n) {
this.number = n
}
MyType.prototype.valueOf = function() {
return this.number
}
MyType.prototype.add = function(a = 0) {
return new MyType(a + this)
}
MyType.prototype.multiply = function(a = 1) {
return new MyType(a * this)
}
const x = new MyType(1)
console.log(x.add(1)) // { number: 2 }
console.log(x.multiply(2)) // { number: 2 }
console.log(x.add(1).multiply(2)) // { number: 4 }
console.log(x.add(1).multiply(2) + 3) // 7
The key thing to note about this is that you are still using your object, but the valueOf on the prototype is what allows you to directly utilize the number as the value of the object, while still making the methods available. This is shown in the last example, where we directly add 3 to it (without accessing number). It is leveraged throughout the implementation by adding this directly to the numeric argument of the method.
Method chaining is the mechanism of calling a method on another method of the same object in order to get a cleaner and readable code.
In JavaScript method chaining most use the this keyword in the object's class in order to access its method (because the this keyword refers to the current object in which it is called)
When a certain method returns this, it simply returns an instance of the object in which it is returned, so in another words, to chain methods together, we must make sure that each method we define has a return value so that we can call another method on it.
In your code above, the function addNumber returns the current executing context back from the function call. The next function then executes on this context (referring to the same object), and invokes the other functions associated with the object. it's is a must for this chaining to work. each of the functions in the function chaining returns the current Execution Context. the functions can be chained together because the previous execution returns results that can be processed further on.
This is part of the magic and uniqueness of JavaScript, if you're coming from another language like Java or C# it may look weird for you, but the this keyword in JavaScript behaves differently.
You can avoid the necessity of this and be able to return a value implicitly, using a Proxy object with a get-trap.
Here you find a more generic factory for it.
const log = Logger();
log(`<code>myNum(42)
.add(3)
.multiply(5)
.divide(3)
.roundUp()
.multiply(7)
.divide(12)
.add(-1.75)</code> => ${
myNum(42)
.add(3)
.multiply(5)
.divide(3)
.roundUp()
.multiply(7)
.divide(12)
.add(-1.75)}`,
);
log(`\n<code>myString(\`hello world\`)
.upper()
.trim()
.insertAt(6, \`cruel coding \`)
.upper()</code> => ${
myString(`hello world`)
.upper()
.trim()
.insertAt(6, `cruel coding `)
.upper()
}`);
log(`<br><code>myString(\`border-top-left-radius\`).toUndashed()</code> => ${
myString(`border-top-left-radius`).toUndashed()}`);
// the proxy handling
function proxyHandlerFactory() {
return {
get: (target, prop) => {
if (prop && target[prop]) {
return target[prop];
}
return target.valueOf;
}
};
}
// a wrapped string with chainable methods
function myString(str = ``) {
const proxyHandler = proxyHandlerFactory();
const obj2Proxy = {
trim: () => nwProxy(str.trim()),
upper: () => nwProxy(str.toUpperCase()),
lower: () => nwProxy(str.toLowerCase()),
insertAt: (at, insertStr) =>
nwProxy(str.slice(0, at) + insertStr + str.slice(at)),
toDashed: () =>
nwProxy(str.replace(/[A-Z]/g, a => `-${a.toLowerCase()}`.toLowerCase())),
toUndashed: () => nwProxy([...str.toLowerCase()]
.reduce((acc, v) => {
const isDash = v === `-`;
acc = { ...acc,
s: acc.s.concat(isDash ? `` : acc.nextUpcase ? v.toUpperCase() : v)
};
acc.nextUpcase = isDash;
return acc;
}, {
s: '',
nextUpcase: false
}).s),
valueOf: () => str,
};
function nwProxy(nwStr) {
str = nwStr || str;
return new Proxy(obj2Proxy, proxyHandler);
}
return nwProxy();
}
// a wrapped number with chainable methods
function myNum(n = 1) {
const proxyHandler = proxyHandlerFactory();
const obj2Proxy = {
add: x => nwProxy(n + x),
divide: x => nwProxy(n / x),
multiply: x => nwProxy(n * x),
roundDown: () => nwProxy(Math.floor(n)),
roundUp: () => nwProxy(Math.ceil(n)),
valueOf: () => n,
};
function nwProxy(nwN) {
n = nwN || n;
return new Proxy(obj2Proxy, proxyHandler);
}
return nwProxy();
}
// ---- for demo ---- //
function Logger() {
const report =
document.querySelector("#report") ||
document.body.insertAdjacentElement(
"beforeend",
Object.assign(document.createElement("pre"), {
id: "report"
})
);
return (...args) => {
if (!args.length) {
return report.textContent = ``;
}
args.forEach(arg =>
report.insertAdjacentHTML(`beforeEnd`,
`<div>${arg.replace(/\n/g, `<br>`)}</div>`)
);
};
}
body {
font: 12px/15px verdana, arial;
margin: 0.6rem;
}
code {
color: green;
}
Is it possible to extend the console object?
I tried something like:
Console.prototype.log = function(msg){
Console.prototype.log.call(msg);
alert(msg);
}
But this didn't work.
I want to add additional logging to the console object via a framework like log4javascript and still use the standard console object (in cases where log4javascript is not available) in my code.
Thanks in advance!
Try following:
(function() {
var exLog = console.log;
console.log = function(msg) {
exLog.apply(this, arguments);
alert(msg);
}
})()
You Can Also add log Time in This Way :
added Momentjs or use New Date() instead of moment.
var oldConsole = console.log;
console.log = function(){
var timestamp = "[" + moment().format("YYYY-MM-DD HH:mm:ss:SSS") + "] ";
Array.prototype.unshift.call(arguments, timestamp);
oldConsole.apply(this, arguments);
};
It's really the same solution some others have given, but I believe this is the most elegant and least hacky way to accomplish this. The spread syntax (...args) makes sure not a single argument is lost.
var _console={...console}
console.log = function(...args) {
var msg = {...args}[0];
//YOUR_CODE
_console.log(...args);
}
For ECMAScript 2015 and later
You can use the newer Proxy feature from the ECMAScript 2015 standard to "hijack" the global console.log.
Source-Code
'use strict';
class Mocker {
static mockConsoleLog() {
Mocker.oldGlobalConsole = window.console;
window.console = new Proxy(window.console, {
get(target, property) {
if (property === 'log') {
return function(...parameters) {
Mocker.consoleLogReturnValue = parameters.join(' ');
}
}
return target[property];
}
});
}
static unmockConsoleLog() {
window.console = Mocker.oldGlobalConsole;
}
}
Mocker.mockConsoleLog();
console.log('hello'); // nothing happens here
Mocker.unmockConsoleLog();
if (Mocker.consoleLogReturnValue === 'hello') {
console.log('Hello world!'); // Hello world!
alert(Mocker.consoleLogReturnValue);
// anything you want to do with the console log return value here...
}
Online Demo
Repl.it.
Node.js users...
... I do not forget you. You can take this source-code and replace window.console by gloabl.console to properly reference the console object (and of course, get rid of the alert call). In fact, I wrote this code initially and tested it on Node.js.
// console aliases and verbose logger - console doesnt prototype
var c = console;
c.l = c.log,
c.e = c.error,
c.v = c.verbose = function() {
if (!myclass || !myclass.verbose) // verbose switch
return;
var args = Array.prototype.slice.call(arguments); // toArray
args.unshift('Verbose:');
c.l.apply(this, args); // log
};
// you can then do
var myclass = new myClass();
myclass.prototype.verbose = false;
// generally these calls would be inside your class
c.v('1 This will NOT log as verbose == false');
c.l('2 This will log');
myclass.verbose = true;
c.v('3 This will log');
I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.
You can override the default behavior of the console.log function using the below approach, the below example demonstrates to log the line number using the overridden function.
let line = 0;
const log = console.log;
console.log = (...data) => log(`${++line} ===>`, ...data)
console.log(11, 1, 2)
console.log(11, 1, 'some')
I have a script that I can't change that makes a lot of console.log calls. I want to add another layer and respond if the calls contain certain strings. This works in Firefox, but throws an "Illegal invocation" error in Chrome on the 4th line:
var oldConsole = {};
oldConsole.log = console.log;
console.log = function (arg) {
oldConsole.log('MY CONSOLE!!');
oldConsole.log(arg);
}
Any ideas how to get around that? I also tried cloning the console...
You need to call console.log in the context of console for chrome:
(function () {
var log = console.log;
console.log = function () {
log.call(this, 'My Console!!!');
log.apply(this, Array.prototype.slice.call(arguments));
};
}());
Modern language features can significantly simplify this snippet:
{
const log = console.log.bind(console)
console.log = (...args) => {
log('My Console!!!')
log(...args)
}
}
I know it's an old post but it can be useful anyway as others solution are not compatible with older browsers.
You can redefine the behavior of each function of the console (and for all browsers) like this:
// define a new console
var console = (function(oldCons){
return {
log: function(text){
oldCons.log(text);
// Your code
},
info: function (text) {
oldCons.info(text);
// Your code
},
warn: function (text) {
oldCons.warn(text);
// Your code
},
error: function (text) {
oldCons.error(text);
// Your code
}
};
}(window.console));
//Then redefine the old console
window.console = console;
You can also use the same logic, but call it off the console object so the context is the same.
if(window.console){
console.yo = console.log;
console.log = function(str){
console.yo('MY CONSOLE!!');
console.yo(str);
}
}
With ES6 new spread operator you can write it like this
(function () {
var log = console.log;
console.log = function () {
log.call(this, 'My Console!!!', ...arguments);
};
}());
Can be simply:
console.log = (m) => terminal.innerHTML = JSON.stringify(m)
#terminal {background: black; color:chartreuse}
$ > <span id="terminal"></span>
<hr>
<button onclick="console.log('Hello world!!')">3V3L</button>
<button onclick="console.log(document)">3V3L</button>
<button onclick="console.log(Math.PI)">3V3L</button>
To fully intercept the console, we can override every methods :
const bindConsole=function(onMessage){
Object.keys(console)
.filter(type=>typeof(console[type])==='function')// *1
.forEach(type=>{
let _old=console[type];
console[type] = function (...args) {
_old.apply(console,args);
onMessage(type,args);// *2
};
});
};
For old browsers :
var bindOldConsole=function(onMessage){
for(var k in console){// *1
if(typeof(console[k])=='function')(function(type){
var _old=console[type];
console[type] = function () {
_old.apply(console,arguments);
onMessage(type,arguments);
};
})(k);
}
};
*1 Looks like console has only methods but better be sure.
*2 You may block cyclic calls to console from onMessage by replacing this line with :
if(!isCyclic())onMessage(type,args);
// es6. Not sure concerning old browsers :(
const isCyclic=function (){
let erst=(new Error()).stack.split('\n');
return erst.includes(erst[1],2);
};
Since I cannot comment (yet) on #ludovic-feltz answer, here is his answer corrected to allow string interpolation in the console :
// define a new console
var console = (function(oldCons){
return {
log: function(...text){
oldCons.log(...text);
// Your code
},
info: function (...text) {
oldCons.info(...text);
// Your code
},
warn: function (...text) {
oldCons.warn(...text);
// Your code
},
error: function (...text) {
oldCons.error(...text);
// Your code
}
};
}(window.console));
//Then redefine the old console
window.console = console;