The following editor will bring you a js es6 series tutorial - transforming the es6 class syntax based on the new.target attribute and es5. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let's follow the editor and take a look.
If the constructor of es5 is not called with new and this points to window, the object's properties will not get the value, so in the past we had to judge this in the constructor. Whether the new keyword is used to ensure that ordinary function calls can copy objects to properties
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() );
In es6, in order to identify function calls, whether new is used Keyword, introduces a new attribute new.target:
1. If the function uses new, then new.target is the constructor
2. If the function does not use new, then new .target is undefined
3. In the es6 class method, when calling, use new, and new.target points to the class itself. If new is not used, it is 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
After using new, new.target is the constructor of Person, then the above example can also be written in the following way:
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
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,报错
The above is the detailed content of JavaScript transforms es6 class syntax based on new.target attribute and es5. For more information, please follow other related articles on the PHP Chinese website!