1.常用new的例子
// Otaku 御宅族,简称宅function Otaku (name, age) {this.name = name;this.age = age;this.habit = 'Games';}// 因为缺乏锻炼的缘故,身体强度让人担忧Otaku.prototype.strength = 60;Otaku.prototype.sayYourName = function () {console.log('I am ' + this.name);}var person = new Otaku('Kevin', '18');console.log(person.name) // Kevinconsole.log(person.habit) // Gamesconsole.log(person.strength) // 60person.sayYourName(); // I am Kevin
从这个例子中,我们可以看到,实例 person 可以:
- 访问到 Otaku 构造函数里的属性
- 访问到 Otaku.prototype 中的属性
例二:
// 返回值不是对象function Otaku (name, age) {this.strength = 60;this.age = age;return 'handsome boy';}var person = new Otaku('Kevin', '18');console.log(person.name) // undefinedconsole.log(person.habit) // undefinedconsole.log(person.strength) // 60console.log(person.age) // 18// 返回值是对象function Otaku (name, age) {this.strength = 60;this.age = age;return {name: name,habit: 'Games'}}var person = new Otaku('Kevin', '18');console.log(person.name) // Kevinconsole.log(person.habit) // Gamesconsole.log(person.strength) // undefinedconsole.log(person.age) // undefined
const newDemo = function() {let obj = {}// 取出构造函数let Constructor = [].shift.call(arguments)// 将 obj 的原型指向构造函数,这样 obj 就可以访问到构造函数原型中的属性obj.__proto__ = Constructor.prototype// this指向当前 obj,并取到返回值let ret = Constructor.apply(obj, arguments)// 返回值是对象 就返回对象,其他的就相当于没返回,默认返回 objreturn typeof ret === 'object' ? ret : obj}// 测试function Otaku (name, age) {this.name = name;this.age = age;this.habit = 'Games';}Otaku.prototype.strength = 60;Otaku.prototype.sayYourName = function () {console.log('I am ' + this.name);}let person = newDemo(Otaku, 'june', '18')console.log(person.name)console.log(person.habit)console.log(person.strength)person.sayYourName();
- 新建了一个对象 obj
- 取出第一个参数,就是我们要传入的构造函数。此外因为 shift 会修改原数组,所以 arguments 会被去除第一个参数
- 将 obj 的原型指向构造函数,这样 obj 就可以访问到构造函数原型中的属性
- 使用 apply,改变构造函数 this 的指向到新建的对象,这样 obj 就可以访问到构造函数中的属性
- 判断返回的值是不是一个对象,如果是一个对象,我们就返回这个对象,如果没有,我们该返回什么就返回什么。
