js es6系列教程 - 基于new.target属性与es5改造es6的类语法

发布时间:2020-10-12 19:32:01 作者:ghostwu
来源:脚本之家 阅读:139

es5的构造函数前面如果不用new调用,this指向window,对象的属性就得不到值了,所以以前我们都要在构造函数中通过判断this是否使用了new关键字来确保普通的函数调用方式都能让对象复制到属性

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中,为了识别函数调用时,是否使用了new关键字,引入了一个新的属性new.target:

1,如果函数使用了new,那么new.target就是构造函数

2,如果函数没有用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这个构造函数,那么上例也可以用下面这种写法:

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的类语法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

推荐阅读:
  1. 分享ES6的7个实用技巧
  2. ZKEYS与云谷IDCSystem主机管理系统哪个好?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

es6 new.target 类语法

上一篇:使用Java8中Optional机制的正确姿势

下一篇:解决pycharm回车之后不能换行或不能缩进的问题

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》