es5的構造函數(shù)前面如果不用new調用,this指向window,對象的屬性就得不到值了,所以以前我們都要在構造函數(shù)中通過判斷this是否使用了new關鍵字來確保普通的函數(shù)調用方式都能讓對象復制到屬性
function Person( uName ){ if ( this instanceof Person ) { this.userName = uName; }else { return new Person( uName ); } } Person.prototype.showUserName = function(){ return this.userName; } console.log( Person( 'ghostwu' ).showUserName() ); console.log( new Person( 'ghostwu' ).showUserName() );在es6中,為了識別函數(shù)調用時,是否使用了new關鍵字,引入了一個新的屬性new.target:
1,如果函數(shù)使用了new,那么new.target就是構造函數(shù)
2,如果函數(shù)沒有用new,那么new.target就是undefined
3,es6的類方法中,在調用時候,使用new,new.target指向類本身,沒有使用new就是undefined
function Person( uName ){ if( new.target !== undefined ){ this.userName = uName; }else { throw new Error( '必須用new實例化' ); } } // Person( 'ghostwu' ); //報錯 console.log( new Person( 'ghostwu' ).userName ); //ghostwu使用new之后, new.target就是Person這個構造函數(shù),那么上例也可以用下面這種寫法:
function Person( uName ){ if ( new.target === Person ) { this.userName = uName; }else { throw new Error( '必須用new實例化' ); } } // Person( 'ghostwu' ); //報錯 console.log( new Person( 'ghostwu' ).userName ); //ghostwuclass Person{ constructor( uName ){ if ( new.target === Person ) { this.userName = uName; }else { throw new Error( '必須要用new關鍵字' ); } } } // Person( 'ghostwu' ); //報錯 console.log( new Person( 'ghostwu' ).userName ); //ghostwu上例,在使用new的時候, new.target等于Person
掌握new.target之后,接下來,我們用es5語法改寫上文中es6的類語法
let Person = ( function(){ 'use strict'; const Person = function( uName ){ if ( new.target !== undefined ){ this.userName = uName; }else { throw new Error( '必須使用new關鍵字' ); } } Object.defineProperty( Person.prototype, 'sayName', { value : function(){ if ( typeof new.target !== 'undefined' ) { throw new Error( '類里面的方法不能使用new關鍵字' ); } return this.userName; }, enumerable : false, writable : true, configurable : true } ); return Person; })(); console.log( new Person( 'ghostwu' ).sayName() ); console.log( Person( 'ghostwu' ) ); //沒有使用new,報錯以上這篇js es6系列教程 - 基于new.target屬性與es5改造es6的類語法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網(wǎng)。
新聞熱點
疑難解答