zoukankan      html  css  js  c++  java
  • 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);
    
  • 相关阅读:
    [学习笔记]信号基本概念(中断和信号)/名称及常用信号/信号处理/signal函数实践
    基于jquery的移动端JS无缝切换
    判断form表单每个input字段是否有内容
    整合常用功能的JS小组件库-v1.0
    获取网页可见区域的宽高(兼容各浏览器)
    判断网页上滚还是下滚
    文字溢出处理
    网页导航条滚动固定
    清除浮动
    CSS文字两端对齐
  • 原文地址:https://www.cnblogs.com/renzhiwei2017/p/9139659.html
Copyright © 2011-2022 走看看