关于js的星星点点(构造函数和普通函数及class)

206 阅读2分钟

1. 构造函数和普通函数的区别

在命名规则上,构造函数一般是首字母大写,普通函数遵照小驼峰式命名法。 在函数调用的时候:

function fn() { }

构造函数:

1. new fn()<br/>
2 .构造函数内部会创建一个新的对象,即f的实例<br/>
3. 函数内部的this指向 新创建的f的实例<br/>
4. 默认的返回值是f的实例<br/>

普通函数:

1. fn()<br/>
2. 在调用函数的内部不会创建新的对象<br/>
3. 函数内部的this指向调用函数的对象(如果没有对象调用,默认是window)<br/>
4. 返回值由return语句决定

构造函数的返回值:

有一个默认的返回值,新创建的对象(实例);
当手动添加返回值后(return语句):
1. 返回值是基本数据类型-->真正的返回值还是那个新创建的对象(实例)
2. 返回值是复杂数据类型(对象)-->真正的返回值是这个对象

2. ES6语法中class和构造函数有什么区别

构造函数:

function handleMath(x, y) {
    this.x = x,
    this.y = y
}

handleMath.prototype.add = function(){
    return this.x + this.y
}
var m = new handleMath(1, 2);
console.log(m.add());

class语法:

class handleMath {
    constructor(x, y){
        this.x = x;
        this.y = y;
    }
    
    add(){
        return this.x + this.y;
    }
}

var m = new handleMath(1, 2);
console.log(m.add());

typeof handleMath 是 function class只是一个语法糖。

是不是有点感觉了?

在来看下继承:

构造函数实现:

function Animal() {
   this.eat = function(){
       console.log('dog eat')
   }
}

function Dog() {
   this.dark = function(){
       console.log('dog dark')
   }
}

Dog.prototype = new Animal();
var dogNo1 = new Dog();
dogNo1.eat();
dogNo1.dark();

class 函数实现

class Animal{
    constructor(name){
        this.name = name;
    }
    eat (){
       console.log('dog eat')
   }
}

class Dog extends Animal{
    constructor(name){
        super(name);
        this.name = name;
    }
    say() {
        console.log(this.name + ' say')
    }
}

var dogNo2 = new Dog('lili');
dogNo2.say();
dogNo2.eat();

总结:

  1. class语法糖更容易理解,更加语义化。
  2. 本质还是使用prototype。