• js 实现继承相关


    【要求】:实现一个Animal类, 和一个继承它的Dog类

    ☛ 【实现】:

    function Animal(name) {
    	this.name = name;
    }
    
    Animal.prototype.cry = function() {
    	console.log('I am ' + this.name);
    }
    
    function Dog(name) {
    	Animal.call(this, name);
    	this.hobby = 'running';
    }
    
    Dog.prototype = new Animal();
    
    // 注意要放在上条语句的下面
    Dog.prototype.run = function() {
    	console.log('I like ' + this.hobby);
    }
    
    var dog = new Dog('doggy');
    dog.run();	// 'I like running'
    dog.cry();	// 'I am doggy'
    

    【要求】:用JS实现一个类继承函数

    function extend(parent){ /*...*/}
    

    ☛ 【实现】:

    function Animal(name) {
    	this.name = name;
    }
    
    Animal.prototype.cry = function() {
    	console.log('I am ' + this.name);
    }
    
    var People = {
    	name: 'bb',
    	say: function() {
    		console.log(this.name);
    	}
    }
    
    function extend(parent) {
    
    	if (typeof parent == 'function') {
    		function child() {
    			parent.call(this, ...arguments);
    		}
    
    		// 可以在 child 的原型上自己定义方法,而不会影响 parent 的原型
    		child.prototype = new parent();
    	}
    
    	if (typeof parent == 'object') {
    		function child() {};
    
    		// 将 parent 作为 child 的原型
    		child.prototype = parent;
    	}
    	
    	return child;
    }
    
    var Pet = extend(Animal);
    var dog = new Pet('doggy'); // child {name: "doggy"}
    dog.name = 'Doggy';
    dog.cry();	// 'I am Doggy'
    
    var Person = extend(People);
    var bob = new Person;   // child {name: "Bob"}
    bob.name = 'Bob';
    bob.say();	// 'Bob'
    
  • 相关阅读:
    1017 A除以B (20分)**
    剑指 Offer 11. 旋转数组的最小数字(简单)
    剑指 Offer 04. 二维数组中的查找(中等)
    剑指 Offer 53
    剑指 Offer 53
    剑指 Offer 03. 数组中重复的数字(简单)
    剑指 Offer 58
    剑指 Offer 05. 替换空格(简单)
    执行npm install命令出错问题
    剑指 Offer 35. 复杂链表的复制(中等)
  • 原文地址:https://www.cnblogs.com/Ruth92/p/5887474.html
Copyright © 2020-2023  润新知