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() );
function Person( uName ){
if( new.target !== undefined ){
this.userName = uName;
}else {
throw new Error( '必须用new实例化' );
}
}
// Person( 'ghostwu' ); //报错
console.log( new Person( 'ghostwu' ).userName ); //ghostwu
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,报错
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有