面向对象,函数构造方法

来源:互联网 发布:unity3d做2d游戏 编辑:程序博客网 时间:2024/06/06 02:52
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>面向对象,函数构造方法1</title></head><body></body><script>/*(function(){}());将变量方法等搞成不同作用域,即封装某些代码块,后加()是为了可以执行*/(function(){var n="局部作用域的变量n";function people(name,age,sex){//people类的构造函数this.name=name;this.age=age;this.sex=sex;}people.prototype.n=n;people.prototype.say=function(){alert("people----say");}window.people=people;//赋值给window,全局才可以调用}());(function(){function stu(name,age,sex){//stu类的构造函数this.name=name;this.age=age;this.sex=sex;}stu.prototype=new people();//继承people类var speple_say=stu.prototype.say;people.prototype.say=function(){speple_say.call(this);//子类调用父类的say()alert("stu----say");//重写父类say()}window.stu=stu;//赋值给window,全局才可以调用}());var p=new people('小明','12','男');p.say();alert(p.name+"  "+p.n);var s=new stu();s.say();alert(s.n);</script></html>

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>面向对象,函数构造方法2</title></head><body></body><script>/*(function(){}());将变量方法等搞成不同作用域,后加()是为了可以执行*/(function(){var n="局部变量n";function people(name){var _this={};//声明_this变量是一个空对象_this.name=name;_this.say=function(){alert("people----say---"+_this.name);}return _this;//个人觉得people更像是一个方法而不是类}window.people=people;}());function stu(name){var _this=people(name);var supersay=_this.say;_this.say=function(){supersay.call(_this);alert("stu----say---"+_this.name);}return _this;}var s=stu('jick');s.say();</script></html>


0 0
原创粉丝点击