Javascript random behavior

Can someone explain this code to me

var ParentClass = function(){
}

var ChildClass = function(){
}

//ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert true

But

var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert false
+3
source share
4 answers

constructoris a property of an object prototype:

var ChildClass = function(){
}

alert(ChildClass.prototype.constructor == ChildClass); // alert true

Now the relation is as follows:

  +-------------------+           +--------------------+
  |                   |           |                    |
  |ChildClass instance|---------->|ChildClass protoype |
  |                   |           |  constructor prop  |
  +-------------------+           +--------------------+

This property points to a function ChildClass.

If you override ChildClass.prototype, then it child.constructorwill be checked in the prototype chain and will refer to:

ParentClass.prototype.constructor

as ChildClass.prototypeit is now an instance ParentClassthat inherits from ParentClass.prototype:

  +-------------------+      +--------------------+      +---------------------+
  |                   |      |                    |      |                     |
  |ChildClass instance| ---> |ParentClass instance| ---> |ParentClass prototype|
  |                   |      |                    |      |   constructor  prop |
  +-------------------+      +--------------------+      +---------------------+

ParentClass.prototype.constructorof course point to ParentClass.

+4
source

, ParentClass! , "javascript patterns" ( javascript).

:

var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

var child = new ChildClass();
alert(child.constructor === ParentClass)

!

+3

. , :

var ChildClass = function () {

}

ChildClass.prototype.OftUsedMethod = function () {
  // Something you'll want to be able to do here for every instance of
  // ChildClass, but that you don't want separate instances of the function
  // for.
}

ChildClass.prototype member, ChildClass.

+1

, . . , John Resig .

var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();
ChildClass.prototype.constructor = ChildClass;

var child = new ChildClass();
alert(child.constructor === ChildClass); // alert true
+1

All Articles