OOP 4个概念
封装 encapsulation
对于方法函数来说,越少参数越好让人理解,因为有class的上下 文。
抽象 abstration
减少暴露的东西。
继承 inheritance
提炼重复代码。
多态 polymorphism
减少if else
prototype原型,介绍
proto是普通的对象。
如果用指定的构造函数创建对象,这些创建对象都会拥有相同的原型(内存中的同一份)。
原型可以拥有多level,比如:myArrary->ArrayBase(push什么的在这里)->元对象。
属性是可配置的,如可写、可枚举。
prototype 继承
function Circle(radius){
this.radius = radius;
this.move = function () {
console.log( ‘move’ );
}
}
// 抽象到原型
Circle.prototype.draw = function() {
console.log( ‘draw’ );
}
const c1 = new Circle(1);
const c2 = new Circle(1);
// 重写toString
Circle.prototype.toString = function() {
return 'Circle with radius ’ + this.radius;
}
// 只返回instance成员
console.log( Object.keys(c1) );
// 返回 instance + prototype
for ( let key in c1 ) console.log(key);
// 会返回false
c1.hasOwnProperty(‘draw’);
避免修改内建原型
Array.prototype.shuffle = function() {
// …
}
不要修改不属于你的对象,这样会产生无法侦测的bug
prototype继承
function Shape(color){
this.color = color;
}
Shape.prototype.duplicate = function () {
console.log(‘duplicate’);
}
function Circle(radius,color){
Shape.call(this, color);// 这里调用基类的构造
this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype); // 保证继承shape
Circle.prototype.constructor = Circle; // 重设该有的constructor
Circle.prototype.draw = function() {
console.log(‘draw’);
}
const s = new Shape();
const c = new Circle();
多态
function extend(Child, Parent){
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
function Shape(){
}
Shape.prototype.duplicate = function() {
console.log(‘d shape’);
}
function Circle(){
}
extend(Circle,Shape);
Circle.prototype.duplicate = function(){
Shape.prototype.duplicate.call(this);
console.log(‘d circle’);
}
function Square(){
}
extend(Square,Shape);
Square.prototype.duplicate = function(){
Shape.prototype.duplicate.call(this);
console.log(‘d square’);
}
const shapes = [
new Circle(),
new Square()
];
for (let shape of shapes)
{
shape.duplicate();
}
Mixins,组合
利用组合来简化继承层级
// mixin
function mixin( target, …sources ){
Object.assign(target, …sources);
}
const canEat = {
eat: function() {
console.log(‘eating’);
}
}
const canWalk = {
walk: function(){
console.log(‘walking’);
}
}
const canSwim = {
walk: function(){
console.log(‘swim’);
}
}
function Person() {
}
mixin(Person.prototype,canEat,canWalk);
const person = new Person();
console.log(person);
function Goldfish(){
}
mixin(Goldfish.prototype,canEat,canSwim);
const goldfish = new Goldfish();
console.log(goldfish);