zoukankan      html  css  js  c++  java
  • js的继承实现方式

    1. 使用call或者apply来实现js对象继承

         function Animal(age){
                this.age = age;
                this.say = function(){
                    console.log('age:'+this.age);
                };
            }    
            function Dog(age,nickname){
                Animal.call(this,age);
                // Animal.apply(this,[age]);
                this.nickname = nickname;
                this.say = function(){
                    console.log('nickname:'+this.nickname+',age:'+this.age);
                };
            }    
            var animal = new Animal(11);
            var dog = new Dog(12,'dog');
            animal.say();
            dog.say();        

    2. 使用原型链来实现js继承;

         function Animal(){}
            Animal.prototype.age = 11;
            Animal.prototype.say = function(){
                console.log('age:'+this.age);
            };
            function Dog(){}
            Dog.prototype = new Animal();
            Dog.prototype.nickname = 'dog';
            Dog.prototype.say =    function(){
                console.log('nickname:'+this.nickname+',age:'+this.age);
            }; 
            var animal = new Animal();
            var dog = new Dog();
            animal.say();
            dog.say();

    3. 使用原型链和apply混合实现。

         function Animal(age){
                this.age = age;
            }    
            Animal.prototype.say = function(){
                console.log('age:'+this.age);
            };
            function Dog(age,nickname){
                Animal.call(this,age);
                // Animal.apply(this,[age]);
                this.nickname = nickname;
            }    
            Dog.prototype.say =    function(){
                console.log('nickname:'+this.nickname+',age:'+this.age);
            }; 
            var animal = new Animal(11);
            var dog = new Dog(12,'dog');
            animal.say();
            dog.say();
  • 相关阅读:
    截取文件路径组成新文件路径
    jsoup选择器
    正则小示例
    一个没有经过优化的过滤指定目录下的指定扩展名文件的算法
    正则表达式生成问题
    链接中带换行的页面查找替换问题
    数组扩容测试
    LeetCode 3.无重复字符的最长子串
    LeetCode 200.岛屿数量
    LeetCode 560.和为K的子数组
  • 原文地址:https://www.cnblogs.com/MorewalkSofar/p/5956026.html
Copyright © 2011-2022 走看看