国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js es6系列教程 - 基于new.target屬性與es5改造es6的類語法

2019-11-19 15:34:52
字體:
來源:轉載
供稿:網(wǎng)友

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 ); //ghostwu
class 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)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 集贤县| 孟连| 沙湾县| 房山区| 铁岭县| 桦甸市| 璧山县| 会同县| 和田市| 包头市| 嘉义县| 道孚县| 同德县| 凤台县| 呼图壁县| 资源县| 沙湾县| 广平县| 巴东县| 保山市| 永丰县| 宜阳县| 长泰县| 衡阳市| 云和县| 久治县| 兴业县| 磐石市| 平武县| 揭西县| 海伦市| 会泽县| 拜泉县| 德阳市| 玉溪市| 陕西省| 汤原县| 怀来县| 宣恩县| 孟村| 奎屯市|