前言 :
面向对象是一种编程的思想,编程语言有面向过程的 C语言,有面向对象的 C++ ,Java 等语言。面向对象主要的特性在于,封装性,继承性,多态性。这里我们来讨论在 JS 面向对象中怎么样去实现多态的。因为在 JS 中名称函数不允许重复,否则会发生覆盖 。所以 JS 中实现 多态,通常有 参数不同 和 类型不同。
- 了解 arguments ?
在 ES5 的时候,JS 函数内部存在一个 arguments 对象。可以通过 arguments.length 获取到实参个数, arguments[x] 获取到第 x 个参数,arguments 是一个对象,可以 通过下标访问 。
function demo(a,b){
console.log(demo.length);// 形参个数
console.log(arguments.length);// 实参个数
console.log(arguments[0]);// arguments 是一个对象,可以通过下标访问
}
demo(5,6,7);
// demo.length = 2
// arguments.length = 3
// arguments[0] = 5
- 参数不同,实现多态 ?
function add(){
var total = 0;
for(var i=0; i<arguments.length; i++){
total += arguments[i];
}
return total;
}
console.log(add(1,2,3,4)); // 10
console.log(add(11,22,33)); // 66
function fontSize(){
var ele = document.querySelector('section');
if(arguments.length === 0){
return ele.style.fontSize;
}else{
ele.style.fontSize = arguments[0];
}
}
fontSize(40);
- 类型不同,实现多态 ?
function setting(){
var ele = document.querySelector('#js');
if(typeof arguments[0] == 'object'){
for(var p in arguments[0]){
ele.style[p] = arguments[0][p];
}
}else{
ele.style.backgroundColor = arguments[1];
ele.style.fontSize = arguments[0];
}
}
setting(12,'red')
setting({fontSize:20,backgroundColor:'green'})
- 运行时,实现多态 ?(JS_运行时多态,方法的重写 )
function demo(o){
o.run();
}
var o = {
run: function(){
console.log('o is running ...');
}
}
demo(o)
var p = {
run: function(){
console.log('p is running ...');
}
}
demo(p)
/* --------------------------------------------- */
// 父类
function Parent(name,age){
this.name = name;
this.age = age;
this.run = function(){
console.log('parent is running ...');
}
Parent.prototype.eat = function(){
console.log('parent is eatting ...');
}
}
// 子类
function Child(name,age,stuno){
Parent.apply(this,arguments);
this.stuno = stuno;
var parentRun = this.run;
this.run = function(){
console.log('child is running ...');
parentRun();
}
}
// 实现父子继承,修改子类 constructor
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.super = Parent.prototype;
// 子类的属性和方法
Child.prototype.eat = function(){
console.log('child is eatting ...');
Child.super.run();
}