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

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:11:57
字體:
供稿:網(wǎng)友

es5的構(gòu)造函數(shù)前面如果不用new調(diào)用,this指向window,對象的屬性就得不到值了,所以以前我們都要在構(gòu)造函數(shù)中通過判斷this是否使用了new關(guān)鍵字來確保普通的函數(shù)調(diào)用方式都能讓對象復(fù)制到屬性

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ù)調(diào)用時,是否使用了new關(guān)鍵字,引入了一個新的屬性new.target:

1,如果函數(shù)使用了new,那么new.target就是構(gòu)造函數(shù)

2,如果函數(shù)沒有用new,那么new.target就是undefined

3,es6的類方法中,在調(diào)用時候,使用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這個構(gòu)造函數(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關(guān)鍵字' );    }   }     }  // 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關(guān)鍵字' );    }   }   Object.defineProperty( Person.prototype, 'sayName', {    value : function(){     if ( typeof new.target !== 'undefined' ) {      throw new Error( '類里面的方法不能使用new關(guān)鍵字' );     }     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的類語法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持錯新站長站。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 莲花县| 辰溪县| 惠来县| 工布江达县| 绵阳市| 定陶县| 虎林市| 秦皇岛市| 霍州市| 安乡县| 伊川县| 陈巴尔虎旗| 新乡市| 元谋县| 保山市| 搜索| 百色市| 故城县| 福海县| 河北省| 东阳市| 上饶市| 麦盖提县| 麟游县| 沙河市| 阿克苏市| 望江县| 松潘县| 城步| 二连浩特市| 周至县| 江城| 浦江县| 密云县| 塘沽区| 桂阳县| 巴马| 共和县| 固阳县| 福鼎市| 巴彦淖尔市|