javascript - 如何限制用户仅使用新运算符调用函数?
问题描述
function person(name){
if(new.target){
new throw('Please call with new operator')
}
this.name = name
}
var a = new person(); // correct wy
person(); // will give error to user
我们可以限制用户仅使用 new
.if调用函数new
吗error
?
你能建议更好的方法吗?
解决方案
您的代码的问题是new.target
仅在使用new
. 条件应该是!new.target
:
function Person(name) {
if (!new.target) throw ('Please call with new operator')
this.name = name
}
var a = new Person('Moses');
console.log(a);
Person();
另一种选择是使用ES6 类。尝试将类作为函数调用会引发错误:
class Person {
constructor(name) {
this.name = name;
}
}
var a = new Person('Moses');
console.log(a);
Person();
推荐阅读
- sql - 如何在 SQLite 中转储表的某些行?
- fortran - 如何读取单列数据并写入表中?
- flutter - Flutter 应用程序:无法返回类型为“Either”的值
" from 方法,因为它的返回类型为 "Either " - javascript - 我的搜索似乎无法弄清楚。我的情况是字符串和数组的问题
- html - 如何使图像自动调整大小以适合之间有边距的线?
- java - 满足某些条件时如何执行 button.setOnTouchListener (Kotlin)
- c# - 使用 HttpClient 或其他 C# 类发送带有密钥库文件的肥皂请求
- sql - PostgreSQL 索引减少了数据大小但使查询变慢
- php - 服务器移动后TYPO3 argon2密码哈希匹配部分不匹配
- r - 在导入之前过滤 CSV 文件以获取特定值