关于javascript:js-new一个对象的过程

2次阅读

共计 744 个字符,预计需要花费 2 分钟才能阅读完成。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>new 一个对象的过程 </title>
</head>
<body>
    <script>
        function newObj(constructor, ...args) {if (typeof constructor !== 'function') throw new Error('第一个参数需是构造函数')
            // setp1: 创立一个空对象 o
            const o = {}
            // setp2:将 o 作为 this 参数调用构造函数 constructor,并接管返回值 result
            const result = constructor.apply(o, args)
            // setp3:设置原型链
            o.__proto__ = constructor.prototype
            // setp4:判断返回值 result 是否为对象类型,是的话返回 result,不是的话返回对象 o
            if (typeof result === 'object') return result
            else return o
        }

        function Person(name, age) {
            this.name = name
            this.age = age
        }

        const p1 = new Person('张三', 20)
        console.log('p1', p1)

        const p2 = newObj(Person, '李四', 30)
        console.log('p2', p2)
    </script>
</body>
</html>

正文完
 0