标签:
JS是一种十分灵活的语言,不谈多态(或者说它本身就是多态的)
封装
概念:
封闭一部分,外界无法直接访问
通过开放部分间接访问私有部分
例子:
不封装:构造函数的所有属性都是开放的
function Girl(name,bf){ this.name = name; this.bf = bf; } var girl = new Girl("林黛玉","贾宝玉"); alert(girl.name + "love" + girl.bf);//林黛玉love贾宝玉
封装:封装部分属性,要靠公共接口才能访问
function Girl(name,bf){ var secret = bf; this.name = name; this.showlove = function(){ return secret; } var girl = new Girl("林黛玉","贾宝玉"); alert(girl.name + "love" + girl.secret);//林黛玉love undefined,secret不可访问 alert(girl.name + "love" + girl.showlove());//林黛玉love贾宝玉,通过开放部分间接访问私有属性
总结:用闭包完成私有属性的封装
继承
一、原型继承
//原型链核心是__proto__ function Dog(){ this.bark = function(){ alert("wangwang") } } function Hashiqi(){ } Hashiqi.prototype = new Dog(); var dog1 = new Hashiqi(); dog1.bark();//wangwang Hashiqi.prototype.bark = function(){ alert("wuwu"); } var dog2 = new Hashiqi(); dog2.bark();//wuwu var dog3 = new Dog(); dog3.bark();//wangwang
二、对象冒充
临时变量
function Parent(){ } function Child(){ this.temp = Parent; this.temp(); delete this.temp; }
call()和apply()
function Parent(){ } function Child(){ Parent.call(this,var1,var2...) //Parent.apply(this,[var1,var2...]) }
三、复制继承
Object.prototype.extend = function(obj){ for(var key in obj){ if(this[key]==undefined){ this[key]=obj[key]; } } } var cat = {color:"yellow",climb:function(){alert("我会爬树");}} var tiger = {color:"yellow and black"} tiger.extend(cat); tiger.climb();//我会爬树 alert(tiger.color);//yellow and black
四、混合继承
静态方法
//这是一个构造函数,也是一个对象 function Bird(){ this.wings=2; this.fly= function(){ alert("我会飞"); } } //这是Bird对象的静态方法,只属于此对象 Bird.eat = function(){ alert("吃虫子") } var niao = new Bird();//Bird的实例,不能访问eat()
标签:
原文地址:http://www.cnblogs.com/dll-ft/p/5568111.html