Is this correct (JavaScript prototype property)?

38 views Asked by At

Here I created a function which will ultimately be used as a constructor for other clones. Aside from the properties arguments, caller, length, name, __proto__(link to Function.protoype) created, the prototype property is created. This property points to the object which will be assigned as the prototype to the instances created when this function is invoked when using the new keyword.

function Clonetrooper(ID, rank, yearsOfService, type){
if (!(this instanceof Clonetrooper)){
    return new Clonetrooper(ID, rank, yearsOfService, type);
}
this.ID = ID;
this.rank = rank;
this.yearsOfService = yearsOfService;
this.type = type;
} 

So when I do this:

Clonetrooper.prototype.hasUtilityBelt = true;
Clonetrooper.prototype.hasLightSaber = false;

I am adding properties on the Clonetrooper prototype property. One by one.

But if I do this afterwards:

Clonetrooper.prototype = {
    name: null
    hasDroid: null

};

I have overwritten the link to the Clonetrooper's constructor replacing it with a new Object which links to Object.prototype.

So my question is, that last syntax is indeed overwriting your prototype property?

So probably one should carefully plan out a object to avoid this occurrence.

1

There are 1 answers

3
Анатолий Ивашов On BEST ANSWER

Yes, we must be careful. In most cases we should extend the existing prototype by one of two ways:

Clonetrooper.prototype.foo = ...

or (e.g. using jQuery)

$.extend(Clonetrooper.prototype, {
    bar: ...,
    baz: ...
})