<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js自动检测是否使用new关键字创建函数</title>
</head>
<body>
<script>
/**
* @dec js 自动检测是否使用new关键字创建函数
* @param name
* @param age
* @returns {Person}
* @constructor
*/
function Person (name, age) {
if (this instanceof Person) {
this.name = name;
this.age = age;
} else {
return new Person(name, age);
}
}
const liubei = Person('liubei', 45);
console.log(liubei.age, liubei.name);// 45 "liubei"
const zhangfei = new Person('zhangfei', 89);
console.log(zhangfei.age, zhangfei.name);// 89 "zhangfei"
</script>
</body>
</html>
js自动检测是否使用new关键字创建函数
最新推荐文章于 2023-08-03 10:20:10 发布