面性对象和继承

时间:2017-10-24 13:46:38   收藏:0   阅读:273

面向对象编程思想需要我们掌握关于类的继承、封装、多态

1、封装:把实现一个功能的代码放在一个函数中封装起来,以后再想实现这个功能的时候,我们不需要重新的编写代码了,只需要执行对应的函数即可,我们把这种机制就称之为"函数的封装" -->低耦合高内聚:减少页面中的冗余代码,提高代码的重复使用率

function fn(){
//实现功能的代码
}
fn();
fn();

2、多态:
后台语言[java、C#、ASP.net、php...]中的多态:重载、重写
重载(Reload):多个方法,方法名相同,参数的个数或者参数的类型不一样
重写(Rewrite):子类重写父类的方法

fn(); ->2
function fn(){console.log(1);}

//根据传递的n和m的值不一样,我们获取的结果也不一样,例如:如果执行的时候不传递任何的参数,返回[0-1)之间的随机小数,如果传递了两个值1/10,返回的是[1-10]之间的随机整数

function getRandom(n,m){
n=Number(n);
m=Number(m);
if(isNaN(n) || isNaN(m)){
return Math.random();
}
if(n>m){
n=m+n;
m=n-m;
n=n-m;
}
return Math.round(Math.random()*(m-n)+n);
}

3、继承:
JS中常用的继承有以下几种方式(子类想要继承父类中的属性和方法)

function Parent() {this.x = 100;}
Parent.prototype.getX = function () {console.log(this.x);};
function Children() {this.x = 200;}
Children.prototype = new Parent;
var c = new Children;
function Parent() {this.x = 100;this.writeX = function () {}}
Parent.prototype.getX = function () {console.log(this.x);};
function Children() {
//this->Children的实例c
Parent.call(this);//把Parent当做普通的函数执行,让里面的this变为c ->在执行的时候相当于c.x=100、c.writeX=function...
}
var c = new Children;
var d = new Children;
console.log(c.writeX === d.writeX);//-->false
function Parent() {this.x = 100;this.writeX = function () {}}
Parent.prototype.getX = function () {console.log(this.x);};
function Children() {
var temp=new Parent();
//temp就是Parent的一个实例:x、writeX、getX
for(var key in temp){
this[key]=temp[key];
}
temp=null;
}
var c = new Children;
var d = new Children;
console.log(c.getX === d.getX);

原型继承和call继承/冒充对象继承,任意一个组合到一起来实现的,一般来说都是和call继承组合

function Parent() {
this.x = 100;
this.writeX = function () {}
}
Parent.prototype.getX = function () {
console.log(this.x);
};
function Children() {
Parent.call(this);
}
Children.prototype = new Parent;
var c = new Children;

 

原文:http://www.cnblogs.com/Scar007/p/7722946.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!