js实现重载和重写

重载

函数重载是指在同一作用域内,可以有一组具有相同函数名,不同参数列表的函数,这组函数被称为重载函数。重载函数通常用来命名一组功能相似的函数,这样做减少了函数名的数量,避免了名字空间的污染,对于程序的可读性有很大的好处。

  • js通过函数名找到对应的函数对象
  • 然后根据函数按照定义时的参数,和表达式参数列表按顺序匹配,多余的参数舍去,不够的参数按undefined处理
  • 然后执行函数代码。
 // 可以跟据arguments个数实现重载
   function add() {
        var sum = 0 ;
        for ( var i = 0 ; i < arguments.length; i ++ ) {
            sum += arguments[i];
        }
        return sum;
    }
    console.log(add()) // 0
    console.log(add(1,2))  // 3
    console.log(add(1,2,3)) // 6

重写

“实例中的指针仅指向原型,而不是指向构造函数”。
“重写原型对象切断了现有原型与任何之前已经存在的对象实例之间的关系;它们引用的仍然是最初的原型”。

var parent = function(name,age){
    this.name = name;
    this.age = age;
}
 
parent.prototype.showProper = function(){
    console.log(this.name+":"+this.age);
}
 
var child = function(name,age){
    parent.call(this,name,age);
}
 
// inheritance
child.prototype = Object.create(parent.prototype);
// child.prototype = new parent();
child.prototype.constructor = child;
 
// rewrite function
child.prototype.showProper = function(){
    console.log('I am '+this.name+":"+this.age);
}

var obj = new child('wozien','22');
obj.showProper();

上面这段代码通过使用寄生组合继承,实现子类私有继承父类私有,子类公有继承父类公有,达到重写父类的showProper

猜你喜欢

转载自www.cnblogs.com/mengxiangji/p/10403097.html