JavaScript对象继承的方法

    写这个话题单纯是给本身作笔记了,否则老忘记。app

    第一种方法:
ide

    function fn1(x) {
        this.x = x;
    }

    function fn2(x, y) {
        this.tmpObj = fn1;
        this.tmpObj(x);
        delete this.tmpObj;
        this.y = y;
    }

    第二种方法:call()或apply()this

    function fn1(x) {
        this.x = x;
    }

    function fn2(x, y) {
        fn1.call(this, x);
        this.y = y;
    }

    第三种方法:原型链继承
spa

    function fn1(x) {
        this.x = x;
    }

    fn1.prototype.y = function() {
        console.log("i am pomelo");
    }

    function fn2() {}

    fn2.prototype = new fn1();
    fn2.prototype.constructor = fn2;
    var fn2Obj = new fn2();
    fn2Obj.y();

    实际用得最多的是第二种和第三种。prototype

    function fn1(x) {
        this.x = x;
    }

    fn1.prototype.z = function() {
        console.log("i am pomelo");
    }

    function fn2(x, y) {
        fn1.apply(this, [x]);
        this.y = y;
    }

    fn2.prototype = new fn1();
    fn2.prototype.constructor = fn2;
    var fn2Obj = new fn2(1024, 2048);
    console.log(fn2Obj.x);
    console.log(fn2Obj.y);
    fn2Obj.z();
相关文章
相关标签/搜索