關於js的星星點點(構造函數和普通函數及class)

1. 構造函數和普通函數的區別

在命名規則上,構造函數通常是首字母大寫,普通函數遵守小駝峯式命名法。 在函數調用的時候:javascript

function fn() { }java

構造函數:函數

1. new fn()<br/>
2 .構造函數內部會建立一個新的對象,即f的實例<br/>
3. 函數內部的this指向 新建立的f的實例<br/>
4. 默認的返回值是f的實例<br/>
複製代碼

普通函數:ui

1. fn()<br/>
2. 在調用函數的內部不會建立新的對象<br/>
3. 函數內部的this指向調用函數的對象(若是沒有對象調用,默認是window)<br/>
4. 返回值由return語句決定
複製代碼

構造函數的返回值:this

有一個默認的返回值,新建立的對象(實例);
當手動添加返回值後(return語句):
1. 返回值是基本數據類型-->真正的返回值仍是那個新建立的對象(實例)
2. 返回值是複雜數據類型(對象)-->真正的返回值是這個對象
複製代碼

2. ES6語法中class和構造函數有什麼區別

構造函數:spa

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語法:prototype

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只是一個語法糖。code

是否是有點感受了?對象

在來看下繼承:繼承

構造函數實現:

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。
相關文章
相關標籤/搜索