UNPKG

code2021-l

Version:

前端自定义工具

49 lines (46 loc) 1.68 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>自定义new与instanceof工具函数</title> </head> <body> <script> /* 1. 自定义new工具函数 语法: newInstance(Fn, ...args) 功能: 创建Fn构造函数的实例对象 实现: 创建空对象obj, 调用Fn指定this为obj, 返回obj 2. 自定义instanceof工具函数 语法: myInstanceOf(obj, Type) 功能: 判断obj是否是Type类型的实例 实现: Type的原型对象是否是obj的原型链上的某个对象, 如果是返回tru, 否则返回false */ </script> <script src="../dist/190719-utils.js"></script> <script> function Person(name, age) { this.name = name this.age = age // 如果构造函数return的是一个对象类型数据, new的结果是return的结果, 否则是新创建的对象 // return {} // return [] // return function (){} return 1 // return undefined } const p = new Person('tom', 12) console.log(p) const p2 = aUtils.newInstance(Person, 'Jack', 13) // new Person('Jack', 13) console.log(p2, p2.constructor) </script> <script> console.log(aUtils.myInstanceOf(p, Object)) // true console.log(aUtils.myInstanceOf(p, Person)) // true console.log(aUtils.myInstanceOf(aUtils.myInstanceOf, Function)) // true console.log(aUtils.myInstanceOf(p, String), aUtils.myInstanceOf(p, Function)) // false false console.log(p instanceof Function) // false </script> </body> </html>