关于构造函数方法声明对象和类的区别

来源:2-2 ES6中的类

soso_crazy

2019-07-04 17:30:28

// 车类
class Car {
    // 构造函数 - (工厂中接头人)
    // 实例化 - (造车的过程) => 类创建对象(实例)的过程

    // whell = 4;

    // 构造函数constructor 可以传递参数,在调用时接收构造函数的参数 new Car('构造函数传递的参数')
constructor(wheel, color, length, width) {
        // this指实例化的对象car1、car2
        // this.属性 在实例化对象上添加属性
        this.whell = wheel;
        this.color = color;
        this.length = length;
        this.width = width;

        this.speed = 0;
    }

    // 加速
    // 添加一个方法,在原型对象上添加方法,Car.prototype对象上添加speedUp方法
    speedUp() {
        this.speed += 1;
    }
}

// constructor是构造方法,调用类的时候需要new
const car1 = new Car(3, '#f00', 20, 40);
const car2 = new Car(33, '#ff0', 88, 99);

console.log(car1, car2);


-----------------------------------------------
function Car(wheel, color, length, width){
        this.whell = wheel;
        this.color = color;
        this.length = length;
        this.width = width;
        this.speed = 0;
}

Car.prototype.speedUp=function(){
    this.speed += 1;
}

var car1=new Car(3, '#f00', 20, 40)


以上这两种方法的区别是什么?


写回答

2回答

好帮手慕言

2019-07-05

同学你好,

1、语法糖可以理解为让代码更易于理解的一种代码写法。

2、比如:类不存在变量提升。所以下面这样写会报错,(相对来说是好事,要先声明再使用)

http://img.mukewang.com/climg/5d1eb2100001374303020126.jpg

如果帮助到了你,欢迎采纳~祝学习愉快~

1

好帮手慕言

2019-07-04

同学你好,本质上是没有区别的。ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,通过class关键字,可以定义类。ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

如果帮助到你,欢迎采纳~祝学习愉快~

0
hoso_crazy
h 什么叫语法糖? 它的绝大部分功能,ES5 都可以做到,那有什么ES5做不到而ES6的Class可以做到?
h019-07-04
共1条回复

0 学习 · 10739 问题

查看课程