欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年09月02日 09:48:46   作者:ghostwu  
下面小編就為大家?guī)硪黄猨s es6系列教程 - 基于new.target屬性與es5改造es6的類語(yǔ)法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

es5的構(gòu)造函數(shù)前面如果不用new調(diào)用,this指向window,對(duì)象的屬性就得不到值了,所以以前我們都要在構(gòu)造函數(shù)中通過判斷this是否使用了new關(guān)鍵字來確保普通的函數(shù)調(diào)用方式都能讓對(duì)象復(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í)別函數(shù)調(diào)用時(shí),是否使用了new關(guān)鍵字,引入了一個(gè)新的屬性new.target:

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

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

3,es6的類方法中,在調(diào)用時(shí)候,使用new,new.target指向類本身,沒有使用new就是undefined

function Person( uName ){
   if( new.target !== undefined ){
    this.userName = uName;
   }else {
    throw new Error( '必須用new實(shí)例化' );
   }
  }
  // Person( 'ghostwu' ); //報(bào)錯(cuò)
  console.log( new Person( 'ghostwu' ).userName ); //ghostwu

使用new之后, new.target就是Person這個(gè)構(gòu)造函數(shù),那么上例也可以用下面這種寫法:

function Person( uName ){
   if ( new.target === Person ) {
    this.userName = uName;
   }else {
    throw new Error( '必須用new實(shí)例化' );
   }
  }
  
  // Person( 'ghostwu' ); //報(bào)錯(cuò)
  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' ); //報(bào)錯(cuò)
  console.log( new Person( 'ghostwu' ).userName ); //ghostwu

上例,在使用new的時(shí)候, new.target等于Person

掌握new.target之后,接下來,我們用es5語(yǔ)法改寫上文中es6的類語(yǔ)法

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,報(bào)錯(cuò)

以上這篇js es6系列教程 - 基于new.target屬性與es5改造es6的類語(yǔ)法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論