js 面向对象继承的两种方式及封装

 

        最近学习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);
不会执行出预期效果。
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值