JS 的继承

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

 

posted @ 2017-05-18 18:51  zhongmeizhi  阅读(285)  评论(0编辑  收藏  举报
欢迎打⭐