Javascript类没有按预期方式确定

cto*_*ife 2 javascript

希望有人能指出我正确的方向.

我不是OOP的新手,但我不熟悉它在Javascript中的工作方式.我理解js中的类是对象的概念.

我正在编写一个脚本,它将编写一些html并允许用户添加或删除一些元素.一切正常,除非你点击"添加复选框"以获取html在最后一个实例中更新的任何实例而不是自身(这使我相信存在某种范围或封装失败).

我已经简化了问题并发布了一个小提琴,单击"添加复选框"作为"颜色"实例,您将看到html被添加到"animals"组中.请注意我在第25行的js评论.

http://jsfiddle.net/XrJ3D/

var CheckboxGroup = function(label){
  return this.init(label);
}
CheckboxGroup.prototype = {
  type: "checkbox",
  label: null,      
  description: null,
  $label: null,              
  init: function(label){
    if(!label) label = "Checkboxes";
    self = this;         
    this.$wrap = $("<div class='checkBoxGroup'></div>");
    this.$label = $("<div>"+label+"</div>").appendTo(this.$wrap);
    this.$options = $("<div></div>").appendTo(this.$wrap); 
    this.$add = $("<div class='n'>Add Checkbox</div>").appendTo(this.$wrap);

    this.$add.click(function(){          
      self.addOption("New Option");
    });

    this.options = [];       
    return this;          
  },
  addOption: function(label){
    $option = $("<div class='c'><input type='checkbox' name='"+label+"'><span class='l'>"+label+"</span></div>").appendTo(this.$options);

    $remove = $("<span class='rm'>x</span>").appendTo($option);        
    $remove.click(function(){
      var r=confirm("Remove Option?");
      if (r==false) return;                    
      $(this).parents('.c').remove();
    });
    this.options.push($option);
    return $option;
  },
  get: function(){
    return this.$wrap;
  }
}

// === CREATE SOME INSTANCES ===

a = new CheckboxGroup("Colors");
a.addOption('red');
a.addOption('green');
a.addOption('blue');    

$('body').append(a.get());

b = new CheckboxGroup("Animals");
b.addOption('dog');
b.addOption('cat');

$('body').append(b.get());
Run Code Online (Sandbox Code Playgroud)

感谢您的任何见解.

Ble*_*der 5

您的self变量是全局变量,将被最后初始化的对象覆盖:

self = this;
Run Code Online (Sandbox Code Playgroud)

var在它之前添加,使其成为您的init函数的本地:

var self = this;
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/XrJ3D/5/