Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 17885

How do javascript decide how to print a class name

$
0
0

I'm trying to write an inheritence logic where I clone an input class and inherit from remaining parent classes. In order to do that, I need to create a new class, deep copying one of the classes exactly. I'm trying to achieve something like:

class Original {static b=1; static test2(){}; test(){}}var CopyClass = DeepCopySomehow(Original)class NotWorking extends Original{}console.log(Object.getOwnPropertyNames(NotWorking))// [ 'length', 'name', 'prototype']console.log(Object.getOwnPropertyNames(Original))// [ 'length', 'name', 'prototype', 'test2', 'b' ]console.log(Object.getOwnPropertyNames(NotWorking.prototype))// ['constructor']console.log(Object.getOwnPropertyNames(Class.prototype))// ['constructor', 'test']

I have something like (simplified):

function inherit(Class1, Class2) {  class Base extends Class1 {...stuff...}  Object.defineProperty(Base, 'name', {value: Class1.name});  copy_props(Base.prototype, Class1.prototype);  copy_props(Base, Class1.prototype);  copy_props(Base.prototype, Class2.prototype);  copy_props(Base, Class2.prototype);}

however, this still keeps the information of "Base" somehow.
Browser side -- Here is a reproducable example:

class SpecificParentName{constructor() {return new Proxy(this, {})}}const Base = class extends SpecificParentName{constructor(...args){super(...args)}}Base.toString = () => SpecificParentName.toString()Object.defineProperty(Base, 'name', {value: SpecificParentName.name});console.log(Base)// class extends SpecificParentName{constructor(...args){super(...args)}}// reasonable output, although I would have wanted it to be just class SpecificParentName if possibleconsole.log(new Base())// Proxy(Base) {} // definitely not desired, because it doesn't point to SpecificParentNameconsole.log(new Proxy(Base, {}))// Proxy(Function) {length: 0, name: 'SpecificParentName', prototype: SpecificParentName}// it's ok since points to SpecificParentName

Nodejs side -- I also had a similar problem in nodejs side before:

class SpecificParentName{}console.log(SpecificParentName)// "[class SpecificParentName]"const Base = class extends SpecificParentName{}console.log(Base)// [class Base extends SpecificParentName]// I'd like this^ to be just "[class SpecificParentName]"// hacky fix on nodejs:const Base2 = class extends SpecificParentName{    static [require('util').inspect.custom]() {return `[class ${SpecificParentName.name}]`}console.log(Base2)// "[class SpecificParentName]"}

so my question is, why and how javascript knows about the variable name I use when defining a class when printing, and is there a way to customize it?


Viewing all articles
Browse latest Browse all 17885

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>