zoukankan      html  css  js  c++  java
  • JS继承

    什么是继承

    • 现实生活中的继承

    • 程序中的继承

    构造函数的属性继承:借用构造函数

     function Person (name, age) {
       this.type = 'human'
       this.name = name
       this.age = age
     }
     ​
     function Student (name, age) {
       // 借用构造函数继承属性成员 
       Person.call(this, name, age)
     }
     ​
     var s1 = Student('张三', 18)
     console.log(s1.type, s1.name, s1.age) // => human 张三 18

    构造函数的原型方法继承:拷贝继承(for-in)

     function Person (name, age) {
       this.type = 'human'
       this.name = name
       this.age = age
     }
     ​
     Person.prototype.sayName = function () {
       console.log('hello ' + this.name)
     }
     ​
     function Student (name, age) {
       Person.call(this, name, age)
     }
     ​
     // 原型对象拷贝继承原型对象成员
     for(var key in Person.prototype) {
       Student.prototype[key] = Person.prototype[key]
     }
     ​
     var s1 = Student('张三', 18)
     ​
     s1.sayName() // => hello 张三

    另一种继承方式:原型继承

     function Person (name, age) {
       this.type = 'human'
       this.name = name
       this.age = age
     }
     ​
     Person.prototype.sayName = function () {
       console.log('hello ' + this.name)
     }
     ​
     function Student (name, age) {
       Person.call(this, name, age)
     }
     ​
     // 利用原型的特性实现继承
     Student.prototype = new Person()
     ​
     var s1 = Student('张三', 18)
     ​
     console.log(s1.type) // => human
     ​
     s1.sayName() // => hello 张三
    
  • 相关阅读:
    Swift使用闭包表达式
    css + html 小知识总结
    关于javascript的误区
    什么是cookie
    css技术和实例
    闭包练习
    web 小知识
    javascript------>(此文转发)
    Spring Boot 系列 @ControllerAdvice 拦截异常并统一处理
    JSR-303 数据校验学习
  • 原文地址:https://www.cnblogs.com/superjishere/p/11727808.html
Copyright © 2011-2022 走看看