Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined result using prototype [javascript]

So I'm learning prototype using javascript, and tried some code :

function Employee(name) { this.name= name; }
var m = new Employee("Bob");
var working= { isWorking: true };
Employee.prototype = working; 
alert(m.isWorking);

Unfortunately, I get an undefined message, instead of the true value. Is there a reason to this result?

I have made several tests. I've concluded that reassigning the prototype object causes any previously created instances of the Employee class to be unable to access any properties found inside the newly assigned prototype. Is this accurate?

like image 439
asdfasdf Avatar asked Dec 08 '15 05:12

asdfasdf


People also ask

Is it possible to generate an undefined value from an object?

No matter the situation, the object always contains the full set of properties: and undefined cannot be generated. The operator nullish coalescing evaluates to a default value when its operand is undefined or null:

What is undefined type in JavaScript?

Undefined type is a type whose sole value is the undefined value. In this sense, typeof operator returns 'undefined' string for an undefined value: Of course typeof works nicely to verify whether a variable contains an undefined value:

Why prototype is a function property?

Because prototype is a property of functions (actually, constructors), since it defines the properties/methods of objects of this class (those which were created from the constructor this prototype belongs). Take a look at this link Thanks for contributing an answer to Stack Overflow!

Why does JavaScript return undefined when a variable is not initialized?

The short answer is that JavaScript interpreter returns undefined when accessing a variable or object property that is not yet initialized. For example: On the other side, null represents a missing object reference.


1 Answers

Changing the prototype will not affect an already created object. It will only affect the objects created based on that object.

There is a property __proto__ which could be used to change the prototype, but its implementation is not required. ES6 does define setPrototypeOf method to change the prototype, but since it's only in ES6 the support may vary.

like image 145
Sami Kuhmonen Avatar answered Nov 02 '22 03:11

Sami Kuhmonen