1.封装
在许多面向对象的语言中,对象封装有语法解析来实现的,这些语言或许提供了private,public,protected等关键字来控制访问权限。
但javascript并没有提供这些关键字,只能通过闭包来改变变量的作用域来实现封装特性
//私有变量 .使用闭包来实现私有变量 var privateObj = (function(){ var __private = ‘mico‘; return { getName: function(){ return __private; } } })(); alert(privateObj.__private); alert(privateObj.getName());
2.多态
封装公共的方法,通过传入不同的对象实例来完成多态
function makeSound( animal ){ if( animal && typeof animal.duckSing == ‘function‘ ) { animal.duckSing(); } } var duck = function(){}; duck.prototype.duckSing = function(){ console.log("duck Singing"); }; var chicken = function(){}; chicken.prototype.duckSing = function(){ console.log("duck Singing"); }; makeSound( new duck() ); makeSound( new chicken() );
3、复制
使用对象的create方法实现复制
function plan(){ this.blood = 100; this.attackLevel = 1; this.denfenceLevel = 1; } var p = new plan(); p.blood = 500; p.attackLevel = 8; p.denfenceLevel = 5; //var p2 = Object.create(p); //console.log(p2); //实现克隆方法兼容 Object.create = Object.create || function(obj){ var F = function(){}; F.prototype = obj; return new F(); }; var p2 = Object.create(p); //console.log(p2);
时间: 2024-10-12 08:58:54