Странное поведение javascript - PullRequest
3 голосов
/ 03 июня 2011

Может кто-нибудь объяснить мне этот код

var ParentClass = function(){
}

var ChildClass = function(){
}

//ChildClass.prototype = new ParentClass();

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

Но

var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

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

Ответы [ 4 ]

4 голосов
/ 03 июня 2011

constructor является свойством объекта prototype:

var ChildClass = function(){
}

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

Отношение теперь выглядит так:

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

Это свойство действительно указывает на ChildClassfunction.

Если вы переопределите ChildClass.prototype, то child.constructor будет найден в цепочке прототипов и будет ссылаться на:

ParentClass.prototype.constructor

, поскольку ChildClass.prototype теперь является экземпляромParentClass который наследуется от ParentClass.prototype:

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

ParentClass.prototype.constructor, конечно, будет указывать на ParentClass.

3 голосов
/ 03 июня 2011

Ну, потому что в этом случае вы заимствуете конструктор из ParentClass!Это шаблон, о котором я читал в книге "Шаблоны javascript" (очень хорошая книга по javascript).

Фактически:

var ParentClass = function(){
}

var ChildClass = function(){
}

ChildClass.prototype = new ParentClass();

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

Предупреждения верны!

1 голос
/ 03 июня 2011

Когда вы перезаписываете прототип объекта, он также перезаписывает конструктор. Вы можете установить его обратно к оригиналу, однако. Это делается с помощью различных библиотек и фрагментов, таких как Simple Inheritance .

Джона Ресига.
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 голос
/ 03 июня 2011

Поведение здесь совсем не странное.Обычно вы видите, что люди делают такие вещи:

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 вместо присвоения атрибуту члена, вы фактически перезаписали базовый прототип для ChildClass.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...