首頁  >  文章  >  web前端  >  es6與es5的建構子有什麼差別

es6與es5的建構子有什麼差別

WBOY
WBOY原創
2022-04-25 17:48:012285瀏覽

區別:1、es6建構子中類別的變數不會被提升,也就是物件只能在類別的定義之後才能創建,而es5中宣告建構子會變數提升;2、es6不可以直接呼叫建構函數,es5中可以直接呼叫建構函數,將構造函數當作普通函數使用。

es6與es5的建構子有什麼差別

本教學操作環境:windows10系統、ECMAScript 6.0版、Dell G3電腦。

es6與es5的建構子有什麼差別

使用建構子建構可以重複使用的物件
建構子就是你建構出來的函數,是一種特殊的方法,與普通函數有著質的區別,其作用,在創建對象的時候主要用來初始化對象,就是給對象成員賦初始值,構造函數的主要特徵就是方法名、首字母大寫,並且用new來使用

ES5

function foo(){
	this.name = 'Katherine';
	this.age  = '26';
}
var f = new foo();
console.log(f)		//Object
console.log(f.name)	//Katherine
console.log(f.age)  //26

function foos(name,age,sex){
	this.name = name;
	this.age  = age;
	this.sex  = sex;
}
var f1 = new foos('Kathrine', '26', 'female');
var f2 = new foos('Stefan', '27', 'male');
var f3 = new foos('Damon', '29', 'male');
console.log(f1) //foos {name: "Kathrine", age: "26", sex: "female"}
console.log(f2) //foos {name: "Stefan", age: "27", sex: "male"}
console.log(f3) //foos {name: "Damon", age: "29", sex: "male"}

ES6

class foo{
	constructor(){
		this.name = 'Karherine';
		this.age  = '26';
	}
	vampire(va){
		console.log('Her name is '+this.name+' and she was '+this.age+' years old')
	}
}
let f = new foo()
	f.vampire();  //Her name is Karherine and she was 26 years old
//继承原型	
class foos extends foo{
	constructor(){
		super();
		this.name = 'Stefan';
		this.age  = '27';
	}
}	
let f1 = new foos();
	f1.vampire();  //His name is Stefan and he was 27 years old

1、ES5可以用new產生對象,也可以直接呼叫建構函數,直接呼叫當成普通函數使用。例如函數foo();

2、ES6必須用new生成對象,不可以直接呼叫建構子成普通函數使用。

與ES5不同,類別的變數不會被提升,也就是說物件只能在類別的定義之後才能創建。

類別的呼叫必須要使用new,而普通的建構子可以當作普通函數來使用。

【相關推薦:javascript影片教學web前端

以上是es6與es5的建構子有什麼差別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn