设计模式-继承模式

该例子使用了两种继承方式,详情可参见https://segmentfault.com/a/11...

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>继承模式</title>
<head>
<body>
  <button onclick="sub()">click me</button>
</body>
</html>

<script type="text/javascript">

//叶子对象的父类
var Field = function(id) {
  this.id = id;
}
Field.prototype.save = function() {
  sessionStorage.setItem(this.id, this.getValue());
  console.log(sessionStorage.getItem(this.id));
}

//因select和textarea的取值方式和input不一样
//所以单独抽离获取值的方法
//如果子类不覆盖此方法,save就会出错,所以用抛异常的方式,保证子类覆盖
Field.prototype.getValue = function() {
  throw new Error('you should override this method');
}


//叶子对象的子类InputField
var InputField = function(label, id, type) {
  //继承父类的id属性,相当于在InputField加上了this.id = id
  Field.call(this, id);
  //创建input节点
  this.input = document.createElement('input');
  this.input.id = id;
  this.input.type = type;
  //创建文本节点
  this.label = document.createElement('label');
  var labelTextNode = document.createTextNode(label);
  this.label.appendChild(labelTextNode);
  //创建div节点
  this.divElement = document.createElement('div');
  this.divElement.className = 'input-field';
  //添加到div节点
  this.divElement.appendChild(this.label);
  this.divElement.appendChild(this.input);
}

//开始继承
function extend(newobj, obj) {
  var F = function() {};
  F.prototype = obj.prototype;
  newobj.prototype = new F();
  newobj.prototype.constructor = newobj;
}

//先得到父类的prototype上的方法
extend(InputField, Field);

//覆盖父类的方法,如果不覆盖,会抛异常
InputField.prototype.getValue = function() {
  return this.input.value;
}

//实验一下
var input = new InputField('用户名', 'userName', 'text');
document.body.appendChild(input.divElement);
function sub() {
  input.save()
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值