• ES5和ES6中实现对象和继承的方法对比


    ES5中创建一个对象(或者叫做类),通常使用构造函数定义实例属性,原型模式用于定义方法和共享属性。对象实例可以访问原型中的值,但不能修改原型中的值。

    function Person(name, age) {
    	this.name = name;
    	this.age = age;
    	this.friends = ['one', 'two']
    }
    Person.prototype = {
    	constructor: Person,
    	sayName: function() {
    		alert(this.name);
    	}
    }
    var p1 = new Person('ren',18);
    var p2 = new Person('zhiwei', 18);
    console.log(p1.friends)
    console.log(p2.friends)
    alert(p1.friends == p2.friends)	// false  new调用构造函数创建了一个新对象,所以friends数组不同
    

    ES6中引入Class概念创建一个类。

    class Person {
        // 相当于 function Person(name, age){......}
    	constructor(name, age) {
    		this.name = name;
    		this.age = age;
    		this.friends = ['one', 'two'];
    	}
    	// 相当于Person.prototype = {...}
    	sayName() {
    		alert(this.name);
    	}
    }
    let p1 = new Person('nihao', 18);
    p1.sayName();
    console.log(p1.friends);
    

    ES5中实现继承,通过在继承的函数中调用call()或者apply()方法实现继承

    function SuperType(name) {
    	this.name = name;
    	this.color = ["red", "blue"];
    }
    SuperType.prototype.sayName = function() {
    	alert(this.name);
    }
    function SubType(name, age) {
    	SuperType.call(this, name);
    	this.age = age;
    }
    SubType.prototype = new SuperType();
    SubType.prototype.constructor = SubType;
    
    var s1 = new SubType('ren');
    s1.sayName();
    console.log(s1.color);
    

    ES6中在constructor()中调用super()可继承基类。

    class SuperType {
    	constructor(name) {
    		this.name = name;
    		this.color = ["red", "blue"];
    	}
    	sayName() {
    		alert(this.name);
    	}
    }
    class SubType extends SuperType {
    	constructor(name, age) {
    	// 相当于SuperType.call(this, name);
    		super(name);
    		this.age = age;
    	}
    }
    var s1 = new SubType('ren', 19);
    console.log(s1);
    
  • 相关阅读:
    Asp.net实现MVC处理文件的上传下载删除功能实例教程
    My WebGrid
    Asp.net MVC3 WebGrid查询绑定
    jquery 使用简明教程
    View-Control-Model基础,强类型视图,添加验证 Sample
    MVC3 DorpDownList
    WARNING: IPv4 forwarding is disabled. Networking will not work.
    KVM虚拟化管理平台WebVirtMgr部署及使用
    error:docker-ce conflicts with 2:docker-1.13.1-74.git6e3bb8e.el7.centos.x86_64
    vue.js插值,插入图片,属性
  • 原文地址:https://www.cnblogs.com/renzhiwei2017/p/9139659.html
Copyright © 2020-2023  润新知