js自动检测是否使用new关键字创建函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15253407/article/details/89882443
<!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>

猜你喜欢

转载自blog.csdn.net/qq_15253407/article/details/89882443
今日推荐