作者:zccst
封装已经上升到写插件的水平了,与多重继承属于同一个高度,来共同完成实际工作中的挑战。
1,封装
//另外:共有变量跟Person构造函数没关系,静态变量跟继承没关系
在JavaScript模式中,也叫即时函数,即定义完立即执行,并返回一个函数。
再慢慢补充细节吧
2,封装+继承
里面牵扯到一个问题:原型方法能调用实例方法?
详见:http://zccst.iteye.com/blog/2077566
封装已经上升到写插件的水平了,与多重继承属于同一个高度,来共同完成实际工作中的挑战。
1,封装
- var Person = (function(){
- //定义私有方法,相当于private方法,只能在内部访问
- function hello(){
- alert('hello world!');
- }
- return function(){
- //定义私有属性,相当于private属性,只能在公有方法内部访问
- var name,age;
- //定义公有方法,相当于public方法,可以在类的实例中方法
- this.getName = function(){
- return name;
- };
- this.setName = function(newName){
- name = newName;
- };
- this.getAge = function(){
- return age;
- }
- this.setAge = function(newAge){
- age = newAge;
- };
- this.say = hello;
- this.introduce = function(){
- alert('my name is :'+this.getName());
- }
- }
- })();
- var p = new Person();
- p.say(); //hello world
- p.setName('xiaoming');
- p.introduce(); //my name is : xiaoming
- //批注:Person本质上是return的那个函数,里面定义了一堆的get和set方法,然后还有私有变量和私有方法。
- //其实私有方法,按照下面的定义方式也一样
- function Person(){
- var name, age;//私有变量
- var method1 = function(){};//私有方法
- var method2 = function(){};
- this.name = name;//实例变量
- this.sayName = function(){//实例方法
- alert(this.name);
- }
- }
//另外:共有变量跟Person构造函数没关系,静态变量跟继承没关系
在JavaScript模式中,也叫即时函数,即定义完立即执行,并返回一个函数。
再慢慢补充细节吧
2,封装+继承
- var Person = (function(){
- //定义私有方法
- function hello(){
- console.log('hello world!');
- }
- return function(){
- //定义私有属性,相当于private属性
- var name,age;
- //定义公有方法,相当于public方法
- this.getName = function(){
- //console.log(name);
- return name;
- };
- this.setName = function(newName){
- name = newName;
- };
- this.getAge = function(){
- //console.log(age);
- return age;
- }
- this.setAge = function(newAge){
- age = newAge;
- };
- this.say = hello;
- this.introduce = function(){
- alert('my name is :'+this.getName());
- }
- }
- })();
- Person.prototype.protoSay = function(){
- this.say();//在原型对象的方法里调用实例方法???
- }
- var Student = function(){
- Person.call(this);
- }
- for(var i in Person.prototype){Student.prototype[i] = Person.prototype[i]}
- var s = new Student();
- console.log(s);//打印结果如下:
- ////getAge: function (){
- ////getName: function (){
- ////introduce: function (){
- ////say: function hello(){
- ////setAge: function (newAge){
- ////setName: function (newName){
- ////__proto__: Object
- s.setName('xiaoli');
- s.getName();//xiaoli
- //s.protoSay();//helloworld
- var p = new Person();
- console.log(p);
- p.protoSay()
里面牵扯到一个问题:原型方法能调用实例方法?
详见:http://zccst.iteye.com/blog/2077566