js的幾種繼承方式

<script type="text/javascript">
    function Person(name, address) {
        this.Name = name;
        this.Address = address;
    }
    Person.prototype.Show = function() {
        return this.Name;
    }

    //使用call 繼承
    function user(name, address) {
        Person.call(this, name, address)
        this.Tel = "134010842**";
    }

    //使用apply 繼承
    function user2(name, address) {
        Person.apply(this, arguments) //apply第二個參數是參數數組,所以可以使用arguments(這是和call的區別)
        this.Tel = "134010842**";
    }

    //使用prototype 繼承
    user3.prototype = new Person(); //建一個基類的對象作爲子類原型的原型,這樣子類纔會繼承父類的方法
    function user3(name, address) {
        Person.apply(this, arguments);
        this.Tel = "134010842**";
    }

    var user1 = new user("江湖小子1", "四川");
    alert(user1.Name + "-" + user1.Tel + "-" + user1.Address);

    var user2 = new user2("江湖小子2", "北京");
    alert(user2.Name + "-" + user2.Tel + "-" + user2.Address);

    var user3 = new user3("江湖小子3", "上海");
    alert(user3.Name + "-" + user3.Tel + "-" + user3.Address);
</script>

Javascript面向對象:

<script type="text/javascript">
    var Bus;
    //構造函數
    if (Bus == undefined) {
       Bus = function(name, num) {
           this.Init(name, num);
       };
    }
    Bus.prototype.Init = function(name, num) {
       this.Name = name;
       this.Num = num;
    }
    //靜態成員
    Bus.City = "靜態北京";
    Bus.GetCity = function() {
        return Bus.City;
    }

    //實例成員
    Bus.prototype.City = "實例北京";
    Bus.prototype.Show = function() {
        return this.Name + "-" + this.Num;
    }

    var bus = new Bus("公交車", "100");
    alert(bus.City);        //實例北京
    alert(bus.Show());      //公交車 - 100
    alert(Bus.City);        //靜態北京
    alert(Bus.GetCity());   //靜態北京
</script>

發佈了22 篇原創文章 · 獲贊 6 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章