3

我在javascript中使用继承。我陷入了一种情况,我必须检查第一个对象是否在第二个对象中继承。例子 :

   function Parent(name)
   {
     var self = this;

     self.Name = name;

     self.Check = function() {
       for(var i = 0; i < ChildCollection.length ;i++)
       {
          //here i want to check whether self is the object which is
          //inherited in ChildCollection[i] 

          alert(true or false);
       }
     }
   }

   function Child(name)
   {
     var self = this;

     Child.prototype.constructor = Child;   

     self.Name = name;
   }

   $(function() {       

      var ChildCollection = new Array()

      for(var i = 1; i <= 2 ;i++)
      {
         Child.prototype = new Parent("TestParent_" + i);              
         var child = new Child("TestChild_" + i);
         ChildCollection.push(child);
      }             

       ChildCollection[1].Check();
    });  

在上面的代码中,我创建了 2 个类ParentChild. 子继承父。我创建了一个ChildCollection包含所有子对象的全局数组。在父类中有一个我想创建的检查函数,它应该循环遍历ChildCollection数组并检查当前对象的含义(self 或 this)是继承还是当前循环子对象的一部分。

为了清楚起见,我调用了对 ChildCollection 的第二个对象的检查,即ChildCollection[1].Check(). 如果我清楚或没有错,那么第一个警报应该是错误的,第二个警报应该是真的。

Please guid me to solve this issue and sorry if i am on totally on wrong track and please explain me what i am doing wrong ?

4

1 回答 1

0

In the above code i have created 2 classes Parent and Child. Child inherit Parent.

The way you're doing that is very, very unusual. You're giving Child a new and different prototype just before every time you use it. That's probably not what you want to do. This other answer here on Stack Overflow provides an example of the "usual" way of doing inheritance in JavaScript. I've also written a helper script called Lineage to reduce the typing involved.

I have create a global ChildCollection Array which contains all child objects.

It's not a global, it's a variable within your ready callback (the function you're passing into $()). It's not accessible from Parent where you've defined Parent, and so this line:

for(var i = 0; i < ChildCollection.length ;i++)

...will fail with a ReferenceError.

You can fix that in one of three ways:

  1. Passing ChildCollection into the Parent contructor as an argument.

  2. Making ChildCollection actually global (which I would avoid).

  3. Moving your Parent and Child functions into your ready callback so they have access to it.

And actually, to avoid creating globals (Parent and Child) but avoid having Parent rely on a pseudo-global, you can combine #1 and #3.

Re the code comment:

here i want to check whether self is the object which is inherited in ChildCollection[i]

I don't know what you mean by "inherited" in that sentence, but if you want to know whether self is in ChildCollection:

var found = false;
for(var i = 0; !found && i < ChildCollection.length; i++) {
    if (ChildCollection[i] === self) {
        found = true;
    }
}
alert(found);
于 2013-03-01T08:57:55.690 回答