• javascript基础拾遗(八)


    1.原型继承
    如何让一个对象继承另一个对象?

    function Language(name){
            this.name = name
            this.score = 8.0
        }
        Language.prototype.popular = function () {
            return this.score/10*100 + '%'
        }
        function FastLanguage() {
            this.speed = '0.01'
        }
    

    FastLanguage是Language的子类,如何让FastLanguage拥有Language的属性呢?
    由继承规则可知,需要让FastLanguage的原型指向Language的原型,即:
    new FastLanguage()---->FastLanguage.prototype---->Language.prototype---->Object.prototype---->null
    如何让FastLanguage的原型指向Language的原型呢?
    需要借助一个中间对象Temp,让FastLanguage.prototype指向新的Temp对象,Temp的原型指向Language的原型即可。

    function Language(name){
            this.name = name
            this.score = 8.0
        }
        Language.prototype.popular = function () {
            return this.score/10*100 + '%'
        }
        function FastLanguage(name) {
    		// this表示FastLanguage对象,绑定this.name的值
            Language.call(this,name)
            this.speed = '0.01'
        }
        function F() {
    
        }
        F.prototype = Language.prototype
        FastLanguage.prototype = new F()
    	// 需要将FastLanguage原型对应的constructor恢复为以前
        FastLanguage.prototype.constructor = FastLanguage
        fastLanguage = new FastLanguage('C')
        console.log(fastLanguage.popular())
    

    运行结果: 80%

    2.原型继承小结
    1)使用call调用父类构造函数,绑定到当前对象的属性值
    2)使用中间对象Temp实现原型链的继承

  • 相关阅读:
    Charles抓包使用教程
    学习规划
    log重复数据
    CNN实现推特文本分类
    conda env
    matplotlib画基础表
    决策树算法
    sklearn实现决策树
    分词与文本预处理工具
    matplotlib作图学习(1)
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/8001260.html
Copyright © 2020-2023  润新知