<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>结算程序</h1>
<p>
<input type="text" placeholder="原价" id="money" />
</p>
<p>
<select id="level">
<option value="0">普通顾客</option>
<option value="1">VIP会员</option>
<option value="2">金卡会员</option>
<option value="3">砖石会员</option>
</select>
</p>
<p>
<input type="button"id="btn" value="结算" />
</p>
<p id="result"></p>
<script src="test_4es5.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>

原型定义对象的方式缺点是较为麻烦,但是好处是创建对象里面不包括变量和方法的声明

原型定义的对象创建的速度快,占用内存小,推荐使用

 function Calculator() {

 }
Calculator.prototype.money = null;
Calculator.prototype.level = null;
Calculator.prototype.pay = function() {
if(this.level == 0) {
return this.money;
} else if(this.level == 1) {
return `${this.money * 0.96}元`;
} else if(this.level == 2) {
return this.money * 0.92;
} else if(this.level == 3) {
return this.money * 0.85;
} else {
throw "会员等级错误";
}
} function DoubleElevenCalculator() { };
DoubleElevenCalculator.prototype = new Calculator();
DoubleElevenCalculator.prototype.pay = function() {
if(this.level == 0) {
var num = Math.floor(this.money / 200);
return `实际需支付${this.money}元,赠送${num}张50元代金券`;
} else if(this.level == 1) {
var num = Math.floor(this.money / 500);
return `实际需支付${this.money*0.9}元,赠送${num}张100元餐券`
} else if(this.level == 2) {
var num = Math.floor(this.money / 300);
return `实际需支付${this.money*0.85}元,赠送${num}张100元代金券`;
} else if(this.level == 3) {
var num = Math.floor(this.money / 200);
return `实际需支付${this.money*0.8}元,赠送${num}张100元代金券`;
} else {
throw "会员等级错误";
}
} var btn = document.querySelector("#btn");
btn.addEventListener("click", function() {
//var calculator = new Calculator();
var calculator = new DoubleElevenCalculator();
calculator.money = document.querySelector("#money").value;
var money = new Number(money);
calculator.level = document.querySelector("#level").value;
var level = new Number(level);
var temp = calculator.pay();
document.querySelector("#result").innerHTML = temp; });
 
 /*
* 发法一new Object()
* 对象只能调用一次,不能重复利用,也不能被继承
*/ /*
var plane = new Object();
plane.speed=800;
plane.fly=function(){
console.log("飞行速度"+this.speed);
}
plane.fly();
*/ /*
* 方法二json
*/
/*
var plane={
speed:800,
fly:function(){
console.log("飞行速度"+this.speed);
}
}
plane.fly();
*/ /*
* 方法3函数模拟类
* 不能继承
*/
/*
function Plane(){
this.speed=800;
this.fly=function(){
console.log("飞行速度"+this.speed);
}
}
var plane =new Plane();
plane.fly();
*/ /*
* 方法4 最好
*/
function Plane() { }
Plane.prototype.speed = null;
Plane.prototype.fly = function() {
console.log("飞行速度" + this.speed);
}
var plane = new Plane();
plane.speed = 800;
plane.fly(); function FightPlane() { }
FightPlane.prototype = new Plane(); //继承父类prototype所有的内容
FightPlane.prototype.fly = function() {
console.log("战斗机飞行速度" + this.speed)
}
plane = new FightPlane();
plane.speed = 2000;
plane.fly();
05-11 02:36