zoukankan      html  css  js  c++  java
  • 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实现原型链的继承

  • 相关阅读:
    async和await
    Promise
    初始flexbox
    制作一个slider动画
    初探React编程逻辑(结合业务需求)
    原型(prototype)和继承(inherit)
    什么是词法环境(lexical scope)
    typeScript是什么
    typeScript基础类型
    原型,原型链,call/apply
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/8001260.html
Copyright © 2011-2022 走看看