ES6是新版本javascript語言的標準,它給咱們帶來了更簡單、更快捷也更容易理解的語法,如箭頭函數、模板字符串等,爲咱們提供新語法以及代碼特性來提高javascript的使用體驗,目前大多數瀏覽器已經支持ES6中絕大多數特性,基於此ES6普及速度至關快,基本成爲業界標準。javascript
ES6推薦使用let聲明變量,相較於var,let聲明的變量會造成一個塊級做用域,其聲明的變量只在局部做用域中起做用:java
var a=1;
{
let b=2;
}
console.log(a);//1
console.log(b);//ReferenceError: b is not defined
複製代碼
let表示聲明變量,而const表示聲明常量,二者都會造成塊級做用域,可是const聲明的變量都會以常量的形式存在,即值一旦肯定就不能修改:node
const a=1;
a=0;
console.log(a);//TypeError: Assignment to constant variable.
複製代碼
const聲明對象時,對象的屬性值能夠被修改:編程
const hero={
name:"stark",
from:"American"
}
hero.name="batman";
console.log(hero);//{name: "batman", from: "American"}
複製代碼
let與const的其餘注意細節:數組
- 1.let和const聲明的變量不具有在預編譯時提高的特性
- 2.let聲明的變量能夠先聲明不賦值
- 3.let和const聲明變量不容許重複聲明
- 4.const在聲明變量時必須初始化
傳統的函數聲明方式包括函數聲明,函數表達式聲明等,而ES6中新增的函數聲明方式:箭頭函數,其簡便直觀的特色,更簡化了開發者的工做複雜度。
箭頭函數最直觀的特色:瀏覽器
- 省略了function函數聲明關鍵字
- 返回值return關鍵字可省
- 其聲明的函數內部this指向其上一級
//傳統的表達式聲明方式
var getSum=function(a,b){
return a+b;
};
getSum(1,2);//3
//箭頭函數
var add=(a,b)=>a+b;
add(1,2);//3
複製代碼
此處函數體只有一條執行語句,函數體return和{}能夠同時省略。箭頭函數只有一個參數時,包裹形參的()也能夠省略:bash
let func=a=>a;
func(666);//666
複製代碼
箭頭函數中的this指向:數據結構
setTimeout(()=>console.log(this),1000);//當前this指window全局對象
複製代碼
ES6以前的字符串處理方式:函數
let sayInfo=(name,fromArea)=>console.log("I am "+name+" and from "+fromArea+".");
sayInfo("Michael","American");//I am Michael and from American.
複製代碼
而採用模版字符串以後:學習
let sayInfo=(name,fromArea)=>console.log(`I am ${name} and from ${fromArea}.`);
sayInfo("Mary","Cuba");//I am Mary and from Cuba.
複製代碼
不難看出,採用模版字符串以後減小了+的拼接工做,下降了代碼量也讓代碼的可讀性更強。
模版字符串的特色以下:
- 數據用``包裹
- 基本的字符串格式化
- 表達式嵌入字符串中進行拼接,用${}來界定
console.log(`<li>學習中心</li>
<li>案例交流</li>
<li>課程分享</li>
`); //<li>學習中心</li>
//<li>案例交流</li>
//<li>課程分享</li>
複製代碼
模版字符串的又一強大之處,輸出後結果會保留數據的原格式。
數組解構
//通常意義上的賦值
let arr=[1,2,3];
let a=arr[0];
let b=arr[1];
let c=arr[2];
複製代碼
數組解構使用數組字面量,且解構操做所有在數組類內完成。
let colors=["red","green","blue"]
let first=colors[0];
let second=colors[1];
console.log(first,second);//red green
複製代碼
在數組解構語法中,咱們經過值在數組中的位置進行選取,且能夠將其存儲在任意變量中,未顯式聲明的元素都會直接被忽略。
在數組解構中可直接跳過變量名,只爲須要的元素提供變量名:
let people=["zhangsan","lisi","wangwu"];
let [,,third]=people;
console.log(third);//wangwu
複製代碼
使用解構賦值語法從people中獲取第3個元素,third前的逗號是前方元素的佔位符,不管數組中的元素有多少個,均可以經過這種方法提取想要的元素,不須要爲每個元素都指定變量名。
變量交換
數組解構語法還有一個獨特的用例:交換兩個變量的值。
//互換變量的值
let a=1,
b=2;
[a,b]=[b,a];
console.log(a,b);//2 1
複製代碼
數組解構賦值看起來像是一個鏡像:賦值語句左側(也就是等號左側)與其餘數組解構示例同樣,是一個解構模式;右側是一個爲交換過程建立的臨時數組字面量。代碼執行過程當中,先解構臨時數組,將b和a的值複製到左側數組的前兩個位置,最終結果是變量互換了它們的值。
- 注意細節:若是右側數組解構賦值表達式的值爲null或undefined,則會致使程序拋出錯誤
默認值
在數組解構賦值表達式中爲數組中的任意位置添加默認值,當指定位置的屬性不存在或其值爲undefined時使用默認值。
let students=["Jane","Mary"];
let [first,second,third="Michael"]=students;
console.log(first,second,third);//Jane Mary Michael
複製代碼
students數組中沒有第三個元素與之對應,可是它有默認值Michael,不會輸出undefined。
嵌套數組解構
嵌套數組解構即在原有數組模式中插入另外一個數組模式,將解構過程深刻到下一個層級。
let students=["Machael",["Jane","Mary"],"Mike"];
let [first,[second,third]]=students;
console.log(first);//Machael
console.log(second,third);//Jane Mary
複製代碼
變量second引用的是students數組中的值"Jane",該元素包含在數組內部的另外一個數組中,因此second與third兩側的方括號是一個必要的解構模式。
數組複製
在ES5中通常使用concat()方法實現對數組的拷貝:
//concat()方法拷貝數組
let colors=["red","green","blue"];
let cloneColors=colors.concat();
console.log(cloneColors); // ["red", "green", "blue"]
複製代碼
在ES6中,能夠經過不定元素的語法來實現相同的目標:
let colors=["red","green","blue"];
let [...cloneColors]=colors;
console.log(cloneColors);
複製代碼
- 在被解構的數組中,不定元素必須爲最後一個條目,在後面繼續添加逗號會致使程序拋出語法錯誤
對象解構賦值
對象字面量的語法形式是在一個賦值操做符左邊放置一個對象字面量:
let node = {
type: "Identifier",
name: "foo"
};
let { type, name } = node;
console.log(type); // "Identifier"
console.log(name); // "foo"
複製代碼
在這段代碼中,node.type的值被存儲在名爲type的變量中;node.name的值被存儲在名爲name的變量中。
解構賦值
上面咱們已經將對象解構應用到了變量的聲明中。然而,咱們一樣能夠在給變量賦值時使用解構語法。
let node={
type:"Identifier",
name:"Mike"
},
type="Literal",
name=5;
//使用解構分配不一樣的值
{type,name}=node;
console.log(type,name);// Identifier Mike
複製代碼
這段代碼中在聲明type與name時初始化了一個值,後面經過解構賦值的方法,從對象中獲取相應值從新爲兩個變量賦值了。
默認值
使用解構賦值表達式時,若是指定的局部變量名稱在對象中不存在,那麼這個局部變量會被賦值爲undefined,與數組解構賦值有類似處。
let student={ name:"Michael"};
let {name,age=20}=student;
console.log(name); //Michael
console.log(age); //20
複製代碼
這段代碼中爲age設置了默認則value,只有當對應student上沒有該屬性或者該屬性值爲undefined時此默認值纔有效。
爲非同名局部變量賦值
若是但願使用不一樣命名的變量來存儲對象屬性的值,ES6的一個擴展語法能夠知足需求:
let hero={
type:"ironman",
name:"stark"
};
let {type:ownType,name:ownName}=hero;
console.log(ownType); //ironman
console.log(ownName); //stark
複製代碼
使用解構賦值來聲明變量ownType與ownName,兩個變量分別存儲hero對象中的type與name的屬性值。
嵌套對象解構
let info={
type:"Identifier",
name:"zhangsan",
friends:{
first:{
age:35,
hobby:"drink"
},
second:{
age:32,
hobby:"smoke"
}
}
};
let { friends:{second}}=info;
console.log(second.age); //32
console.log(second.hobby); //somke
複製代碼
在解構模式中使用了{},其含義爲在對象中找到friends屬性後,繼續深刻一層查找second屬性,並最終獲取到賦值運算符右側的屬性值。
對象解構模式能夠應用於任意層級深度的對象,且每一層都具有同等的功能。
擴展運算符在數組中的應用
let arr=[...[1,2,3]];
console.log(arr); //[1,2,3]
複製代碼
利用擴展運算符實現數組的複製,即淺拷貝。
function getNum(x,y,z){
//遍歷arguments對象
for(var i=0;i<arguments.length;i++){
console.log(arguments[i]);// 4 5 6
}
//轉化前爲僞數組
console.log(Array.isArray(arguments));//false
let newArguments=[...arguments];
//轉化後爲真數組
console.log(Array.isArray(newArguments));//true
};
getNum(4,5,6);
複製代碼
利用擴展運算符將僞數組轉化爲真數組。
除此以外擴展運算符還能夠用於合併數組:
let arr1=[1,2];
let arr2=[3,4];
console.log(...arr1,...arr2); //1 2 3 4
複製代碼
注意細節:擴展運算符使用時必須有容器包裹,不然會致使系統拋出錯誤。
複製代碼
擴展運算符在對象中的應用
let student={
name:"Jane",
sex:"woman",
friends:["Mary","Mike"]
};
let newStudent={...student};
//let newStudent=Object.assign({},student);等同於擴展運算符方法
console.log(newStudent); //{name: "Jane", sex: "woman", friends: Array(2)};
複製代碼
與數組中的實現功能類似,完成了新對象對舊對象的淺拷貝。此外擴展運算符也能夠用於對象的合併:
let info1={ name:"Mike" };
let info2={ hobby:"write" };
let studentInfo={ ...info1,...info2};
console.log(studentInfo);// {name: "Mike", hobby: "write"};
複製代碼
與數組的擴展運算符同樣,其後能夠跟表達式:
const obj={
...(1<2?{a:1}:{a:2}),
b:2,
};
console.log(obj); // {a: 1, b: 2}
複製代碼
若是擴展運算符後面是一個空對象,則沒有任何效果:
let obj={...{},a:1};
console.log(obj); //{a:1}
複製代碼
若是擴展運算符的參數是null或undefined,這兩個值編譯時會被忽略,不會報錯:
let emptyObj={...null,...undefined}; //不會報錯
複製代碼
對象的擴展運算符與解構賦值的結合使用:
let {x,y,...z}={x:1,y:2,m:3,n:4};
console.log(x,y,z);//1 2 {a:3,b:4};
複製代碼
上述代碼中變量z對應的是解構賦值所在的對象,它獲取賦值運算符右邊全部還沒有讀取的屬性,連通屬性值一統拷貝過來。因爲解構賦值要求等號右邊是一個對象,因此若是等號右邊是 undefined 或 null,就會報錯,由於它們沒法轉爲對象。
1.trim() : 用於除去字符串中空白符
let str=' a bc de ';
console.log(str.trim()); // "a bc de"
console.log(str.trimLeft()); // "a bc de "
console.log(str.trimRight()); //" a bc de"
複製代碼
2.repeat() : 字符串重複次數
let str="12345";
console.log(str.repeat(2)); // "1234512345"
複製代碼
3.includes() :是否包含傳入參數,返回布爾值
let str="hello world";
console.log(str.includes("h")); // true
console.log(str.includes("z")); //false
複製代碼
4.starts/endsWith():是否已傳入參數開頭/結尾,返回布爾值
let str="hello world";
console.log(str.startsWith("hello")); // true
console.log(str.endsWith("xyz")); // false
複製代碼
5.padStart/End():接收兩個參數,第一個參數爲填充以後的字符串長度,第二個參數爲填充元素
let str="abc def";
console.log(str.padStart(15,"*")); // ********abc def
console.log(str.padEnd(20,"-")); // abc def-------------
複製代碼
1.Array.from()
function getNum(x,y,z){
console.log(Array.isArray(arguments));//false
console.log(Array.isArray(Array.from(arguments)));//true
};
getNum(1,2,3);
複製代碼
使用Array.from轉化前判斷結果爲false,並非真正的數組,而轉化後結果爲true,已經從類數組轉變爲了真正的數組。
2.Array.of()
做用:將一組值轉換爲數組,主要目的是彌補構造器Array的不足
以前利用new操做符建立數組:
let arr1=new Array(3);
let arr2=new Array("3");
console.log(arr1,arr2);// [empty × 3] ["3"]
複製代碼
從輸出結果能夠看出咱們的初衷並非建立一個長度爲3的空數組,這就是Array構造器建立數組的缺陷。
利用Array.of新建數組:
let arr1=Array.of(3);
let arr2=Array.of("3");
console.log(arr1,arr2); // [3] ["3"]
複製代碼
Array.of()完美解決了Array構造器的缺陷,而且簡化了利用構造器建立數組的操做。
3.find()與findIndex()
find()用於找出第一個符合條件的數組元素,找不到則會返回undefined
let infoArr=[
{name:"Lucy",score:85},
{name:"Jane",score:78},
{name:"Michael",score:80}
];
//返回name屬性爲Jane的對象
let result=infoArr.find(item=>item.name=="Jane");
console.log(result); // {name: "Jane", score: 78}
複製代碼
- 注意細節:find()不會返回多個值,找到一個符合條件的元素就會返回。
findIndex():返回第一個符合條件的數組元素的索引,沒有符合條件的則會-1。
let infoArr=[
{name:"Lucy",score:85},
{name:"Jane",score:78},
{name:"Michael",score:80}
];
//返回score屬性值爲80的元素的索引
let result=infoArr.findIndex(item=>item.score==80);
console.log(result); // 2
複製代碼
4.includes()
includes()用於判斷數組中是否包含該元素,並返回一個布爾值。
let arr=[1,2,3];
let result1=arr.includes(2);
let result2=arr.includes("a");
console.log(result1,result2);// true false
複製代碼
indexOf()用於查找元素在數組中的索引值,基於此也能夠實現與includes相似的功能:
let arr=[1,2,3];
let result1=arr.indexOf(2);
let result2=arr.indexOf('b');
console.log(result1,result2); //1 -1
複製代碼
經過其返回的索引值結果咱們也能夠判斷出數組中是否存在該元素,可是它對NaN的判斷不許確。
let arr=[1,NaN,3,6];
let result1=arr.indexOf(NaN);
console.log(result1); //-1
let result2=arr.includes(NaN);
console.log(result2); //true
複製代碼
5.fill()
做用:給數組填充指定值,能夠用於數組初始化
let arr=new Array(5);
console.log(arr.fill("*")); //["*", "*", "*", "*", "*"]
複製代碼
使用fill()填充數組具備覆蓋性:
let arr =Array.of(1,2,3);
console.log(arr.fill("a")); // ["a", "a", "a"]
複製代碼
此外fill()還能夠接收第二個和第三個參數,用於指定數據填充位置。
let arr =Array.of("a","b","c");
console.log(arr.fill("d",2,3)); // ["a", "b", "d"]
複製代碼
Set與數組形式類似,也是一種數據集合,區別在於它存儲的值都是惟一的不能重複。建立一個Set實例:
let s1=new Set();
複製代碼
使用Set時傳入數據有兩種方式,一種爲初始化時以數組形式傳入,另外一種爲使用add()方法添加。
let s1=new Set([1,2,3,true]);
s1.add(4,"a");
console.log(s1); // {1, 2, 3, true, 4,"a"}
複製代碼
對於Set中數據的遍歷,能夠採用數組中的forEach方法:
let s1=new Set([1,2,3,true]);
s1.forEach(item=>console.log(item));// 1 2 3 true
複製代碼
此外對於Set數據結構,還有一種for of方法:
let s1=new Set(["a","b","c"]);
for(let item of s1){
console.log(item); // a b c
};
複製代碼
注意細節:Set本質上並非一個數組。
let s1=new Set([1,2,3]);
console.log(Array.isArray(s1)); //false
console.log(typeof s1);//object
複製代碼
由輸出結果不難發現,Set不是數組,而是形式上與數組相似的對象,即類數組。
利用Set中數據的惟一性,咱們能夠輕鬆的實現數組的去重工做:
let s1=new Set([1,1,2,2,3,3,4,4]);
console.log(s1); //{1, 2, 3, 4}
let arr=[1,2,5,3,1,3,NaN,false,NaN];
//Set與擴展運算符結合使用,完成數組去重後的淺拷貝
let newArr=[...(new Set(arr))];
console.log(newArr);// [1, 2, 5, 3, NaN, false]
複製代碼
Map也相似於對象,區別在於對象中的鍵名即屬性名只能是字符串,而Map中存放的鍵能夠是任意值。
建立一個Map實例:
let m1=new Map();
複製代碼
Map存放數據的方式與數組、對象等其餘數據結構都有差異:
let m=new Map([
["name","Mike"],
["area","American"],
[false,"hello"]
]);
console.log(m);// {"name" => "Mike", "area" => "American", false => "hello"}
複製代碼
除這種初始化方式外,還能夠利用set添加數據:
let m=new Map();
m.set(true,"xyz");
m.set([1,2,3],{name:"stark"});
console.log(m);// {true => "xyz", Array(3) => {…}}
複製代碼
既然有set添加數據,相應的必然有get獲取數據:
let m=new Map([
["a","hello"],
[1,"world"],
[false,"xyz"]
]);
m.set([1,2,3],{name:"Michael"});
console.log(m.get("a"),m.get(1)); // hello world
console.log(m.get([1,2,3])); // undefined
複製代碼
注意細節:m.get([1,2,3])獲取不到值的緣由:get()比較的是棧區中的地址。
利用set添加數據時若是有重複的鍵,後面的會覆蓋掉前面的。
Map結構遍歷
Map 結構原生提供三個遍歷器生成函數和一個遍歷方法:
const map=new Map([
["a","hello"],
["b","world"]
]);
for(let key of map.keys()){
console.log(key); // a b
};
for(let value of map.values()){
console.log(value); // hello world
};
for(let item of map.entries()){
console.log(item[0],item[1]); //a hello b world
};
map.forEach((item,index)=>console.log(item,index)); // hello a world b
複製代碼
1.建立class類
在JavaScript中,建立實例對象的傳統方法是經過構造函數生成:
function Hero(name,height,country){
this.name=name;
this.height=height;
this.country=country;
};
Hero.prototype.sayInfo=function(){
console.log(`My name is ${this.name} and come from ${this.country}.`);
};
let stark=new Hero("stark",178,"American");
stark.sayInfo(); // My name is stark and come from American.
複製代碼
上面這種寫法與傳統的面嚮對象語言差別很大,很容易讓初學者產生困惑。
基本上,ES6 的class能夠看做只是一個語法糖,它的絕大部分功能,ES5 均可以作到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向對象編程的語法而已。用class改寫傳統的構造函數法:
//定義Hero類
class Hero{
//定義構造方法
constructor(name,height,country){
this.name=name;
this.height=height;
this.country=country;
};
//定義方法
sayInfo(){
console.log(`My name is ${this.name} and come from ${this.country}.`);
};
};
let stark=new Hero("stark",178,"American");
stark.sayInfo(); // My name is stark and come from American.
複製代碼
ES6中的類,徹底能夠能夠看作構造函數的另外一種簡單寫法,類的使用方法也與構造函數一致,直接對類使用new操做符建立實例對象。
2.constructor方法
constructor
方法是類的默認方法,經過new操做符建立實例對象時自動調用該方法。一個類必須有constructor
方法,若是沒有顯式定義,一個空的constructor
方法會被默認添加。
class Study{
}
//等同於
class Study{
constructor(){}
}
複製代碼
上面定義了一個空的類Study,JS引擎在編譯時會自動爲它添加一個空的constructor
方法。
constructor
方法默認返回實例對象,可是咱們能夠在constructor
內部指定返回特定對象。
let obj={};
class Cat{
constructor(){
return obj;
}
};
console.log(new Cat() instanceof Cat);//false
複製代碼
上面的類中constructor
方法返回了另外一個空對象,因此新建立的實例對象的構造器並不指向Cat類。
ES6中的類與構造函數有諸多類似之處,它們的一個主要區別就是類必須使用new操做符來調用,而構造函數即便調用時沒有new操做符也不會報錯。
class Cat{
constructor(){}
};
Cat(); // TypeError: Class constructor Cat cannot be invoked without 'new'
複製代碼
3.class表達式
與函數中同樣的是,類也可使用表達式的形式定義:
let NewClass=class OldClass{
getName(){
return OldClass.name;
}
};
複製代碼
使用表達式定義一個類,這個類的名字是NewClass而不是oldClass,oldClass只在class的內部代碼可用,指代當前類。
let class1=new NewClass();
console.log(class1.getName()); // OldClass
console.log(OldClass.name); // ReferenceError: OldClass is not defined
複製代碼
輸出結果表示,OldClass只在class內部可以訪問到。
採用類的表達式寫法,能夠寫出當即執行的class類:
let Lucy=new class{
constructor(name){
this.name=name;
}
sayName(){
console.log(`I am ${this.name}.`)
}
}('Lucy');
Lucy.sayName(); // I am Lucy.
複製代碼
4.class中的繼承
ES6以前傳統意義上的繼承:
function Hero(name,country){
this.name=name;
this.country=country;
};
Hero.prototype.sayName=function(){
console.log(`My name is ${this.name} and from ${this.country}.`);
};
function HeroAbility(name,country,ability){
//使用call繼承父對象的屬性
Hero.call(this,name,country);
this.ability=ability;
};
//使用淺拷貝繼承父對象的方法
for(let p in Hero.prototype){
HeroAbility[p]=Hero.prototype[p];
};
//定義子對象的方法
HeroAbility.prototype.sayDetail=function(){
console.log(`My name is ${this.name} and from ${this.country} and have ability of ${this.ability}.`)
};
(new HeroAbility("superman","American","fly").sayDetail());
//My name is superman and from American and have ability of fly.
複製代碼
使用ES6 class中的extends實現繼承:
class Hero{
constructor(name,country){
this.name=name;
this.country=country;
};
sayName(){
console.log(`My name is ${this.name} and from ${this.country}.`);
};
};
class HeroAbility extends Hero{
constructor(name,country,ability){
//繼承父類的屬性
super(name,country);
this.ability=ability;
};
sayDetail(){
console.log(`My name is ${this.name} and from ${this.country} and have ability of ${this.ability}.`)
};
};
(new HeroAbility("Batman","American","Batcar").sayDetail());
//My name is Batman and from American and have ability of Batcar.
複製代碼
constructor
方法中出現的super
關鍵字,表示父類的構造函數,用來新建父類的this
對象。
子類必須在constructor
方法中調用super
方法,不然新建實例時會報錯,這是由於子類本身的this
對象,必須先經過父類的構造函數完成塑造,獲得與父類一樣的實例屬性與方法,而後再加上自身的屬性與方法。若是不調用super
方法,子類就得不到this
對象。
1.屬性相關方法
Object.defineProperty():精細化設置一個對象的屬性
let obj={};
Object.defineProperty(obj,"age",{
value:20, //默認值
writable:true, //可否修改
enumerable:true, //是否可枚舉
configurable:false //可否刪除
});
console.log(obj); //{age: 20}
複製代碼
Object.getOwnPropertyDescriptor():返回指定對象全部自身屬性(非繼承屬性)的描述對象。
let obj={ name:"Miacael" };
console.log(Object.getOwnPropertyDescriptor(obj,"name"));
//{value: "Miacael", writable: true, enumerable: true, configurable: true}
複製代碼
Object.defineProperties():精細化設置一個對象的多個屬性
let obj={};
Object.defineProperties(obj,{
"name":{
value:"wangcai",
writable:true,
enumerable:true,
configurable:false,
},
"address":{
value:"Canada",
writable:true,
enumerable:true,
configurable:false,
}
});
console.log(Object.getOwnPropertyDescriptor(obj,"name"));
//{value: "wangcai", writable: true, enumerable: true, configurable: false}
console.log(Object.getOwnPropertyDescriptor(obj,"address"));
//{value: "Canada", writable: true, enumerable: true, configurable: false}
複製代碼
Object.getOwnPropertyNames():以數組形式返回自身的屬性
let obj = {
name:"Lucy",
from:"Canada"
};
console.log(Object.getOwnPropertyNames(obj)); // ["name", "from"]
複製代碼
Object.keys():與Object.getOwnpropertyNames()功能相似
let obj = {
name:"Kang",
from:"China"
};
console.log(Object.keys(obj)); // ["name", "from"]
複製代碼
Object.values():以數組形式返回對象的屬性值
let obj = {
name:"Kang",
from:"China"
};
console.log(Object.values(obj)); // ["Kang", "China"]
複製代碼
2.繼承相關方法
Object.create():從一個現有對象進行繼承獲得一個全新的對象,新對象能夠訪問舊對象的屬性與方法
function Person(name){
this.name=name;
};
Person.prototype.Say=function(){
console.log(`I am ${this.name}.`)
};
let p1=new Person("xiaozhang");
let p2=Object.create(p1);
p2.name="xiaowang";
console.log(p2.Say()); // I am xiaowang.
複製代碼
Object.getPrototypeOf():用於獲取指定對象的構造器的prototype屬性
var obj={};
var arr=[];
console.log(Object.getPrototypeOf(obj)===Object.prototype); // true
console.log(Object.getPrototypeOf(arr)===Array.prototype); // true
複製代碼
防篡改方法
Object.preventExtensions():不容許新增,能夠刪除和修改
let obj={ name:"xiaoming" };
Object.preventExtensions(obj);
obj.sex="man";
console.log(obj); // {name: "xiaoming"}
複製代碼
Object.seal():不容許新增與刪除,能夠修改
let obj1={name:"xiaoqiang"};
Object.seal(obj1);
obj1.sex="man";
obj1.name="xiaogang";
delete obj1.name;
console.log(obj1); // {name: "xiaogang"}
複製代碼
Object.freeze():不容許新增、刪除與修改
let obj2={name:"xiaohong"};
Object.freeze(obj2);
obj2.hobby="read";
delete obj2.name;
obj2.name="xiaoming";
console.log(obj2); // {name:"xiaohong"}
複製代碼
3.對象的簡寫
對象屬性的簡寫:
條件:屬性的值爲變量且變量名稱與鍵名一致
let name="Lucy",age=20;
let obj={
name, //等同於name:name
age //等同於age:age
};
console.log(obj); // {name: "Lucy", age: 20}
複製代碼
對象中方法的簡寫
let obj1={
//簡寫前
sayHello:function(){
console.log("Hello...");
},
//簡寫後
sayHi(){
console.log("Hi...");
}
};
obj1.sayHello(); // Hello...
obj1.sayHi(); // Hi...
複製代碼
4.Object.assign()
用於對象的合併,將源對象的全部的可枚舉屬性,複製到目標對象。
let target={};
let source1={
name:"Michael",
age:22
};
let source2={
name:"Mary",
};
console.log(Object.assign(target,source1,source2)); // {name: "Mary", age: 22}
複製代碼
注意細節:
- 第一個參數是目標對象,assign這個方法把其它的參數中的屬性所有加在第一個參數身上。
- 第一個參數在屬性複製過程當中,能夠會被修改,後面的會覆蓋前面的屬性。
- assign這個方法的返回值就是第一個參數的引用,也就是返回了第一個參數。
- assign不能拷貝繼承過來的屬性與不可枚舉的屬性。
ES6中的內容遠不止列舉出的這些,上文僅爲前一階段學習的總結,但願與正在學習JS的同窗一同進步,一塊兒提升。