最近学习js面向对象,一直不理解继承及封装,通过查看文字资料及视频资料,现总结如下。
第一种方式:通过 prototype:student.prototype = new Person();
function Person(name){ this.name = name; } Person.prototype.say = function(){ alert("per_hello" + this.name); } function student(){ this.name = name; } student.prototype = new Person(); var supersay = student.prototype.say; student.prototype.say = function(){ supersay.call(this); alert("stu_hello" + this.name); } var s = new student(); s.say();
第二种方式:通过直接赋值: var _this = Person(name);
function Person(name){ var n = "ding"; var _ren = {}; _ren.name = name; _ren.sayhello = function(){ alert("P_hello" + _ren.name + n ); } return _ren; } function Teacher(){ var _this = Person(name); var supersay = _this.sayhello; _this.sayhello = function(){ supersay.call(_this); alert("T_hello" + _this.name); } return _this; } var t = Teacher("imi"); t.sayhello();
这一部分是封装。
(function(){ function Person(name){ var n = "ding"; var _ren = {}; _ren.name = name; _ren.sayhello = function(){ alert("P_hello" + _ren.name + n ); } return _ren; } window.Person = Person; }()); function Teacher(){ var _this = Person(name); var supersay = _this.sayhello; _this.sayhello = function(){ supersay.call(_this); alert("T_hello" + _this.name); } return _this; } var t = Teacher("imi"); t.sayhello();
封装其实 就是用()将function放里面,然后最后加()让它能自己执行自己,同时window.Person = Person; 让它能被调用。
总结一下这三个,其实实现的东西都一样只是表现形式不一样,需要注意的是子类中可以定义一个和父类相同的方法,但执行结果是只执行子类的方法,即子类定义的覆盖了父类的方法。如果想调用父类的方法可以通过
var supersay = _this.sayhello;
supersay.call(_this);
进行访问及调用。
封装中即第三个,定义的
var n = "ding";只能在其封装函数的内部使用,即:
alert("P_hello" + _ren.name + n );不能在外部使用,即:
alert("T_hello" + _this.name);
不能写成alert("T_hello" + _this.name + n);
不会执行出预期效果。