js 函数对象的继承 inherit 带 插件完整解析版

前言:

        本人纯小白一个,有很多地方理解的没有各位大牛那么透彻,如有错误,请各位大牛指出斧正!小弟感激不尽。

        本篇文章为您分析一下原生JS的对象继承方法

需求分析:

 1. 普通用户功能

 2. 会员用户功能

 3. 会员用户需要拥有普通用户的所有功能,并且自身也要有自己的功能

JS行为:


        /**
         * 普通用户构造函数
         * @param {*} firstName 
         * @param {*} lastName 
         * @param {*} age 
         */
        function User(firstName, lastName, age) {
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.fullName = this.firstName + " " + this.lastName;
        }
        // 普通用户构造函数的方法
        User.prototype.sayHello = function () {
            console.log(`大家好,我叫${this.fullName}, 加年${this.age}了`);
        }

        /**
         * 会员用户构造函数
         * @param {*} firstName 
         * @param {*} lastName 
         * @param {*} age 
         * @param {*} money
         */
        function VIPUser(firstName, lastName, age, money) {
            User.call(this, firstName, lastName, age);
            this.money = money;
        }
        VIPUser.prototype.upgrade = function () {
            console.log(`使用了${100}元软妹币升级了`);
            this.money -= 100;
        }

        var vUser = new VIPUser("晓", "佰", 10, 100);  // 调用构造函数


看看效果

  


因此我们需要使用对象继承的方式来处理他
先来看看vUser的目前指向

  

下面是完整代码:
代码虽少,理解不易

/**
 * 对象的继承
 * @param {Function} son 子类构造函数
 * @param {Function} father 父类构造函数
 */
this.myPlugin.inherit = function (son,father) {
    son.prototype = Object.create(father.prototype);
    son.prototype.constructor = son;
    son.prototype.uber = father.prototype;
}


调用函数:
这个函数一定要在最开始调用,因为他会改变他的原型
如果你在后面调用了,他肯定会覆盖了你原来的原型结构 son.prototype = Object.create(father.prototype);


下面进行分析第一步:
Object.create是es5的方法
以前使用的是函数和创建一个新对象等方式
son.prototype = Object.create(father.prototype);

  


就形成了下图的结构:

  


第一步完成后我们在页面打印看看结果:

  

下面进行分析第二步:
son.prototype.constructor = son;

  !

在页面上打印看看:

  

添加上第二步的代码
我们在页面上打印vUser.__proto__.constructor看看效果

  

第三步:
为了方便子类来获取父类的原型
我们在子类中添加一个属性来保留父类的原型
在页面上打印子类的父类看看
  

下面附上雅虎公司优化的继承方式:

/**
 * 雅虎公司的继承
 * @param {Function} son 子类构造函数
 * @param {Function} father 父类构造函数
 */
this.myPlugin.inherit = (function () {
    var Temp = function () { };
    return function (son, father) {
        Temp.prototype = father.prototype;
        son.prototype = new Temp();
        son.prototype.constructor = son;
        son.prototype.uber = father;
    }
}());

结语

整完!!

猜你喜欢

转载自www.cnblogs.com/qq4297751/p/12616334.html