zoukankan      html  css  js  c++  java
  • 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'
    
  • 相关阅读:
    iOS学习13之OC NSString类
    iOS之08-核心语法
    iOS学习12之OC属性和点语法
    iOS学习11之OC继承
    iOS之07-三大特性之多态 + NSString类
    iOS学习10之OC类和对象
    swift(三)字典数组操作
    swift(二)swift字符串和字符和逻辑运算
    swift(二)swift字符串和字符和逻辑运算
    swift(一)基础变量类型
  • 原文地址:https://www.cnblogs.com/Ruth92/p/5887474.html
Copyright © 2011-2022 走看看