面向对象,继承机制

一.面向对象语言的要求

1.封装:把相关的信息(无论数据或者方法)存储在对象中的能力。

2.聚集:把一个对象存储在另一个对象内的能力。

3.继承:由另一个类(或者多个类)得来类的属性和方法的能力。

4.多态:编写能以多种方法运行的函数或者方法的能力。

二.继承机制

1.单个类继承

function ClassA(sColor,sName) {
                this.sayColor = function () {
                    alert(sColor);
                };
                this.sayColordd = function () {
                    alert(sName);
                };
            }

            function ClassB(sColor,sName) {
                this.newMethod = ClassA;
                this.newMethod(sColor,sName);
                delete this.newMethod;
            
                this.name = sName;
                this.sayName = function () {
                    alert(this.name);
                };
            }
            var objA = new ClassA("blue");
            var objB = new ClassB("red", "John");
            objA.sayColor();    //输出 "blue"
            objB.sayColor();    //输出 "red"
            objB.sayColordd();      //输出‘john’;
            objB.sayName();        //输出 "John"

2.多个类继承

function ClassZ() {
    this.newMethod = ClassX;
    this.newMethod();
    delete this.newMethod;

    this.newMethod = ClassY;
    this.newMethod();
    delete this.newMethod;
}

这里存在一个弊端,如果存在两个类 ClassX 和 ClassY 具有同名的属性或方法,ClassY 具有高优先级。因为它从后面的类继承。除这点小问题之外,用对象冒充实现多重继承机制轻而易举。

三.call()方法

1.call()方法是与经典的对象冒充方法最相似的方法,它的第一个参数作用this的对象,其他参数都是直接传递给函数自身。例如

扫描二维码关注公众号,回复: 1675861 查看本文章
function ClassB(sColor, sName) {
    //this.newMethod = ClassA;
    //this.newMethod(color);
    //delete this.newMethod;
    ClassA.call(this, sColor);

    this.name = sName;
    this.sayName = function () {
        alert(this.name);
    };
}

要与继承机制的对象冒充方法一起使用该方法,只需将前三行的赋值、调用和删除代码替换即可:

三.apply()方法

1.apply() 方法有两个参数,用作 this 的对象和要传递给函数的参数的数组。例如:

function ClassB(sColor, sName) {
    //this.newMethod = ClassA;
    //this.newMethod(color);
    //delete this.newMethod;
    ClassA.apply(this, arguments);

    this.name = sName;
    this.sayName = function () {
        alert(this.name);
    };
}

同样的,第一个参数仍是 this,第二个参数是只有一个值 color 的数组。可以把 ClassB 的整个 arguments 对象作为第二个参数传递给 apply() 方法:

猜你喜欢

转载自www.cnblogs.com/MJ-MY/p/9208231.html