12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- <!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>自定义构造函数模式</title>
- </head>
- <body>
- <!--
- 方式四:自定义构造函数模式
- *套路:自定义构造函数,通过new创建对象
- *适用场景:需要创建多个类型确定的对象
- *问题:每个对象都有相同的数据,浪费内存
- -->
- <script>
- //定义类型
- function Person(name, age) {
- this.name = name
- this.age = age
- this.setName = function (name) {
- this.name = name
- }
- }
- var p1 = new Person('孙悟空', 22)
- p1.setName('二师兄')
- console.log(p1.name, p1.age)
- console.log(p1 instanceof Person)
- function Student(name, price) {
- this.name = name
- this.price = price
- }
- var s = new Student('张三', 900)
- console.log(s instanceof Student)
- var p2 = new Person('唐僧', 99)
- console.log(p1, p2)
- </script>
- </body>
- </html>
|