pery mimon
pery mimon

Reputation: 8335

Hide the `prototype` property from override native function by custom function

when native method customized by js function like that

console.log = function myLog(args){...}

or using Object.definePropery(...) then

'prototype' in console.log == true

Are there is a way to hide the prototype key so it feel more like native function ?

so

'prototype' in console.log == false

Upvotes: 1

Views: 99

Answers (2)

Bergi
Bergi

Reputation: 664969

You could delete the property:

console.log = function myLog(args){…};
delete console.log.prototype;

Alternatively, create a function that doesn't have a .prototype in the first place by not using a function expression:

console.log = {log(args) {…}}.log;

console.log = (args) => {…};

Upvotes: 2

4m1r
4m1r

Reputation: 12552

GetOffMyLawn is correct. Object prototype is frozen

> Object
[Function: Object]
> Object.prototype
{}
> Object.prototype = null;
null
> Object.prototype
{}

As would be Function

> Function instanceof Object
true
> Function.prototype
[Function]
> Function.prototype = null;
null
> Function.prototype
[Function]

In order to re-assign a prototype you'll need to instantiate your own Object. I think by default new Objects will not have any frozen properties, including prototype.

> function Test() {}
undefined
> const test = new Test();
undefined
> test
Test {}
> test.prototype
undefined
> test.prototype = null
null
> test instanceof Function
false
> test instanceof Object
true
> test instanceof Test
true
> test.prototype
null
> Object.prototype = test.prototype
null
> Object.prototype
{}
> Object.prototype.whoo = 'whoo';
'whoo'
> Object.prototype
{ whoo: 'whoo' }
> test.prototype = Object.prototype
{ whoo: 'whoo' }
> test.prototype
{ whoo: 'whoo' }

By design Object.prototype is not writable, enumerable or configurable (frozen). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

Upvotes: -1

Related Questions