JS之new

142 阅读1分钟

感谢讶羽大大的分享,想看原文移步讶羽大大的GitHub

new

new运算符创建一个用户定义的对象类型或具有构造函数的内置对象类型之一。

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) // Kevin
console.log(person.habit) // Games
console.log(person.strength) // 60

person.sayYourName(); // I am Kevin

初步实现:

分析:

因为new的结果是一个对象,所以实现的时候我们也要建立一个新对象,假设这个对象叫obj,obj也会具有Otaku构造函数的属性。就使用Otaku.apply(obj,arguments)来给obj添加新的属性。

// 第一版代码
function objectFactory() {

    var obj = new Object(),

    Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    Constructor.apply(obj, arguments);

    return obj;

};

返回值效果实现

假如构造函数有返回值:

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) // Kevin
console.log(person.habit) // Games
console.log(person.strength) // undefined
console.log(person.age) // undefined

构造函数返回对象,在实例person中只能访问返回对象的属性。

如果我们只返回一个基本类型的值呢?

function Otaku (name, age) {
    this.strength = 60;
    this.age = age;

    return 'handsome boy';
}

var person = new Otaku('Kevin', '18');

console.log(person.name) // undefined
console.log(person.habit) // undefined
console.log(person.strength) // 60
console.log(person.age) // 18

结果完全颠倒,尽管有返回值,但相当于没有返回值进行处理。

所以我们还需要判断返回的值是不是一个对象,如果是对象,我们就返回这个对象,如果不是,该返回什么就返回什么。

// 第二版的代码
function objectFactory() {

    var obj = new Object(),

    Constructor = [].shift.call(arguments);

    obj.__proto__ = Constructor.prototype;

    var ret = Constructor.apply(obj, arguments);

    return typeof ret === 'object' ? ret : obj;

};