Object Using the name of the prototype function name instead of its property

I created two functions A and B. Made A a prototype of B. jsfiddle

function A(){ } function B(){ this.name ="Class B"; } B.prototype = A; var b = new B(); alert(b.name); // expected Class B got A 

I know I should have used B.prototype = new A();

Is the behavior expected higher? Is it possible to get "class B" instead of "A" in the above scenario?

Note: I am using the above because A has some property associated with it as A.text = "Text" A.text1 = "Text2" , and I want this property to be available to B. therefore B.prototype == A.prototype. cannot be used.

+4
source share
2 answers

Look at a possible duplicate . What is the reason for using the 'new' keyword in Derived.prototype = new Base , as well as this answer about why there are no β€œclasses” in javascript.

Yes, behavior is expected. B.prototype object your instance of b inherits from is an object of function A Thus, it inherits its name property , which is the string "A" .

And this property is immutable (its property descriptor is {configurable: false, enumerable: false, value: "B", writable: false} ), so when you try to assign a new value to b.name , this will check for [[CanPut]] , which returns false - and nothing happens. in strict mode, an Invalid assignment in strict mode TypeError will be thrown ( demo ).

You can only overwrite it using Object.defineProperty .


@Edit: I'm not sure why you want these properties to be inherited b . They are the "static attributes" of constructor A function, and they must remain there. There is currently no way to allow functions to inherit from anything other than Function.prototype , so either you copy them or you don't use them. Tell us what you need and we can find a solution.

Changing the prototype property of functions (and objects in general) does not make them inherit from anything else. The prototype property of functions indicates the object from which newly created (built) instances will be inherited.

+2
source

If you want B inherit from A , write:

 B.prototype = Object.create( A.prototype ); 
0
source

Source: https://habr.com/ru/post/1447831/


All Articles