JS的prototype、apply、call

來源:互聯網
上載者:User

標籤:obj   color   自己的   輸出   類的方法   on()   ack   效果   用法   

1:原生鏈:prototype

  兒子能夠繼承父親的屬性,也可以覺得遺傳基因不好自己改屬性,(但是不能改變老爸的屬性)。

看例子:

            function farther(){
                    this.name = "jack",
                    this.sex = "man",
                    this.age = 18;
                    this.cbo = function(){
                        console.log(this.name);
                    }
                }
//    繼承
                farther.prototype = {
                    son:function(){
                        this.name = "jack-two";
//  使用自己的name和父類的sex
                        console.log(this.name +"\t"+ this.sex);
//    更改父類的方法。              
                        this.cbo = function(){
                            console.log("cbo change.");
                        };
                        this.cbo();
                    }
                }
                new farther().cbo();    // 輸出 jack
                new farther().son();    // 輸出jack 和 jack-two 加 man 加 cbo change.
                new farther().cbo();    // 輸出的值依然是 jack;子類不能更改父類屬性 

2:call(list) 和 apply(arry) :

  用法1: 對象1.方法.call(對象2),

        對象1的方法使用對象2的屬性,

  用法2: 對象1.call(對象2); 對象2.對象1的方法,

        在對象2中使用對象1的方法。

用法不一樣,效果是一樣的,一個缺少方法,一個缺少屬性。

  為什麼要把 call 和 apply 放一起呢?因為他們除了參數,其效果是一樣的。

            function NameShowing(sex, age) {
                this.showName = function() {
                    console.log(this.name + "\t" + sex + "\t" + age);
                }
            }
            function Person(name) {
                this.yourCC = function(){
                    console.log(name)
                }
                this.name = name;
            };
//    執行個體化對象
            var nameShowing = new NameShowing();
            var jeremy = new Person("Jeremy")
//替換this指向 jeremy
            NameShowing.apply(jeremy, ["girl",18]);
            jeremy.showName();
//    當然可以利用 call(this) 來聯合2個對象            
            function cExent(name,sex,age) {
                NameShowing.call(this,sex,age);
                Person.call(this,name);
            }
//    這會執行fobj
            var c2 = new cExent("jack","man",18);
//    調用NameShowing的myName方法            
            c2.showName();        
            c2.yourCC("my name is jack");    // 輸出 jack,因為執行個體化的時候用的是jack

 

JS的prototype、apply、call

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.