如何在javascript中的另一个对象中声明Object原型

时间:2016-04-28 15:37:47

标签: javascript jquery

我想学习如何以良好的方式做到这一点,如果你能帮助展示实现这一目标的正确方法,我将不胜感激!我以这种方式组织代码的原因是我希望最终将所有内容都包含在一个Object中,在这种情况下是' Helper'。这个顶级对象需要能够拥有子对象,这些子对象可以让我轻松地组织/处理顶级对象可以访问的信息。

第1步:假设我有一个名为Helper的Javascript对象:

 function Helper() {
        var hello = "I'm here to help you!";    
        var cleaners = []; //will contain Cleaning objects
      }

第2步:我想为其添加一些功能:

Helper.prototype = {
  constructor:Helper,
  sayHi:function () {
    return this.hello;
  },
  getCleaners:function() {
    return this.cleaners;
  }
}

第3步:现在让我们说要为Helper添加一个名为Cleaner的对象

Helper.prototype.Cleaner = function(something) {
     this.something = 'I will clean '+something; // ?
   }

- 或 - (不知道该怎么做)

Helper.prototype = {
  constructor:Helper,
  sayHi:function () {
    return this.hello;
  },
  getCleaners:function() {
    return this.cleaners;
  },
  Cleaner:function(something) {
   this.something = 'I will clean '+something; // ? does this refer to Helper or Cleaner? Does it work?
  }
}

第4步:我想将一个toString()函数添加到Cleaner

Cleaner.prototype.toString = function() {
      return 'something: '+this.something; //?
   }
 -or- //not sure how to do this either

  Helper.prototype = {
      constructor:Helper,
      sayHi:function () {
        return this.hello;
      },
      getCleaners:function() {
        return this.cleaners;
      },
      Cleaner:function(something) {
       this.something = 'I will clean '+something; // ? does this refer to Helper or Cleaner? 
      },
      Cleaner.prototype.toString:function() {
          return 'my task: '+this.something; //?
       }
    }

第5步:这就是我想要使用Cleaner对象的方式

Helper.prototype.doSomething = function(something) {
  var cleaner = new this.Cleaner(something);
  this.cleaners.push(cleaner);
}

第6步:以及我希望如何使用Helper对象

var helper = new Helper();
helper.doSomething(something);
console.log(helper.sayHi());
$.each(helper.getCleaners(), function(index, value) {
  console.log($(this).value);
});

0 个答案:

没有答案