Skip to content

Commit 7f5bb9d

Browse files
joyeecheungBridgeAR
authored andcommitted
console: bind methods from the prototype chain in Console
In 62232361 we made the console.Console function construct an object with methods from Console.prototype bound to the instance, instead of with methods found on the prototype chain to be bound on the instances, thus breaking users overriding these methods when subclassing Console because they are not expecting this function to construct a namespace whose methods are not looked up from the prototype chain. This patch restores the previous behavior since it does not affect the characteristics of the global console anyway. So after this patch, the Console function still constructs normal objects with function properties looked up from the prototype chain but bound to the instances always. PR-URL: #24047 Reviewed-By: John-David Dalton <john.david.dalton@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
1 parent b2b0645 commit 7f5bb9d

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

lib/console.js

+4-1
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,10 @@ function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
132132
var keys = Object.keys(Console.prototype);
133133
for (var v = 0; v < keys.length; v++) {
134134
var k = keys[v];
135-
this[k] = Console.prototype[k].bind(this);
135+
// We have to bind the methods grabbed from the instance instead of from
136+
// the prototype so that users extending the Console can override them
137+
// from the prototype chain of the subclass.
138+
this[k] = this[k].bind(this);
136139
}
137140
}
138141

test/parallel/test-console-instance.js

+6
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,16 @@ out.write = err.write = (d) => {};
105105
{
106106
class MyConsole extends Console {
107107
hello() {}
108+
// See if the methods on Console.prototype are overridable.
109+
log() { return 'overridden'; }
108110
}
109111
const myConsole = new MyConsole(process.stdout);
110112
assert.strictEqual(typeof myConsole.hello, 'function');
111113
assert.ok(myConsole instanceof Console);
114+
assert.strictEqual(myConsole.log(), 'overridden');
115+
116+
const log = myConsole.log;
117+
assert.strictEqual(log(), 'overridden');
112118
}
113119

114120
// Instance that does not ignore the stream errors.

0 commit comments

Comments
 (0)