Dowemo
0 0 0 0

An oop problem was encountered when a written test was encountered in the front section, and it wasn't able to jump out of the answer page using the ide. After that, carefully think about the subject and feel the basic understanding of the recognition surface, but it's much more important. After you've done this, you feel that the basic use of oop still has a certain consolidation. The original question is as follows:


The code is as follows:

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}`)
The knowledge points involved in the :

First, you must override the tostring ( ) method of the object in the form of the console output issue.

A cash3 survey is mainly a method of object instance, which inherits from the constructor of the constructor, namely cash cash, prototype rather than the co

A cash4 is directly added to the cash box constructor, which isn't inherited by the instance, and can only be invoked by the constructor;

A cash5 survey is actually a string stitching using the"+"operator on an object, which implicitly calls the object 's tostring ( ) method, returning a string;

:

The original question requires writing a class class, which is the traditional es5 constructor pattern and prototype pattern, because it isn't familiar to es6 尴尬

Now, look at es6.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs