• 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'
    
  • 相关阅读:
    P1182 数列分段 Section II 题解
    P3853 路标设置题解
    二分模板
    P2678 跳石头题解
    P2440 木材加工题解
    P1024 一元三次方程求解题解
    快速下载vscode的方法
    P1824 进击的奶牛题解
    P1873 砍树题解
    用户登录之asp.net cookie的写入、读取与操作
  • 原文地址:https://www.cnblogs.com/Ruth92/p/5887474.html
Copyright © 2020-2023  润新知