前段时间答某笔试的时候遇到一道oop的题,当时不能跳出答题页面用IDE本地调试,所以没有做出来。下来之后仔细思考了一下那道题,感觉考察的知识面虽然基础,但是知识点挺多。把这道题做了一遍之后感觉对oop的基础用法还是有了一定的巩固。原题如图:
代码如下:
function Cash (cash) {
this.total = typeof cash == 'number' ? cash : getTotal(cash);
this.yuan = Math.floor(this.total / 100);
this.jiao = Math.floor(this.total % 100 / 10);
this.fen = Math.floor(this.total % 100 % 10);
}
Cash.prototype.toString = function () {
return `${this.yuan}元${this.jiao}角${this.fen}分`;
}
Cash.prototype.add = function (cashObj) {
var o = new Cash(this.total + cashObj.total);
o.toString = function () {
return `${o.yuan}元${o.jiao}角${o.fen}分,`;
}
return o;
}
Cash.add = function (obj1, obj2) {
var o = new Cash(obj1.total + obj2.total);
o.toString = function () {
return `${o.yuan}元${o.jiao}角${o.fen}分,`;
}
return o;
}
function getTotal (str) {
var yuan = 0,
jiao = 0,
fen = 0;
for (var i = 1; i < str.length; i++) {
if (str[i] == '元') {
yuan += +str[i - 1]
} else if (str[i] == '角') {
jiao += +str[i - 1];
} else if (str[i] == '分') {
fen += +str[i - 1];
}
}
return yuan * 100 + jiao * 10 + fen;
}
const cash1 = new Cash(105);
const cash2 = new Cash(66);
const cash3 = cash1.add(cash2);
const cash4 = Cash.add(cash1, cash2);
const cash5 = new Cash(cash1 + cash2);
console.log(`${cash3}`, `${cash4}`, `${cash5}`)
涉及到的知识点:
首先要想控制台输出题中要求的形式,必须重写对象的toString()方法;
cash3考察的主要是对象实例的方法,是继承自构造函数的原型对象,即Cash.prototype而不是构造函数Cash本身;
cash4则是直接为Cash构造函数添加一个add方法,这个方法是不会被实例所继承的,只能通过构造函数进行调用;
cash5考察的是对对象使用"+"操作符实际进行的是字符串拼接,会隐式调用对象的toString()方法,返回一个字符串;
后续思考:
原题要求的是写一个Class类,而这里的实现采用的是传统的ES5构造函数模式和原型模式,因为对ES6的class语法糖还不甚熟悉
接下来要去看ES6啦!