JavaScript “类”风格与对象关联委托

 结果:

 

类风格代码

function Widge(width, height) {
  this.width  = width || 50;
  this.height = height || 50;
  this.$elem = null;
}

Widge.prototype.render = function($where) {
  if(this.$elem) {
    this.$elem.css({
      width: this.width + "px",
      height: this.height + "px"
    }).appendTo($where);
  }
};

function Button(width, height, label) {
  Widge.call(this, width, height);
  this.label = label || "Default";
  this.$elem = $("<button>").text(this.label);
}

Button.prototype = Object.create(Widge.prototype);

Button.prototype.render = function($where) {
  Widge.prototype.render.call(this, $where);
  this.$elem.click(this.onClick.bind(this));
}

Button.prototype.onClick = function(evt) {
  console.log( "Button '" + this.label + "' clicked!" );
}

$(function() {
  var $body = $(document.body);
  var btn1 = new Button(125, 30, "Hello");
  var btn2 = new Button(150, 40, "World");

  btn1.render($body);
  btn2.render($body);
});

 

对象关联委托

var Widge = {
  init: function(width, height) {
    this.width = width || 50;
    this.height = height || 50;
    this.$elem = null;
  },
  insert: function($where) {
    if(this.$elem) {
      this.$elem.css({
        width: this.width + "px",
        height: this.height + "px"
      }).appendTo($where);
    }
  }
};

var Button = Object.create(Widge);

Button.setup = function(width, height, label) {
  this.init(width, height);
  this.label = label || "Default";
  this.$elem = $("<button>").text(this.label);
};

Button.build = function($where) {
  this.insert($where);
  this.$elem.click(this.onClick.bind(this));
};

Button.onClick = function(evt) {
  console.log("Button " + this.label + " clicked!");
};

$(function() {
  var $body = $(document.body);
  
  var btn1 = Object.create(Button);
  btn1.setup(125, 30, "Hello");

  var btn2 = Object.create(Button);
  btn2.setup(150, 40, "World");

  btn1.build($body);
  btn2.build($body);
});

 

转载于:https://www.cnblogs.com/dreamerjdw/p/6272982.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值