js中new关键字实现

145 阅读1分钟

原型模式

原型模式不单是一种设计模式,也被成为一种编程泛型。在原型编程的思想中,一个对象是通过克隆另一个对象所得到的。在js中来实现克隆对象的方法是Object.create()方法。

var Plane = function () {
	this.boole = 100;
	this.attackLeve = 1;
	this.defenseLeve = 1;
}

var plane = new Plane();

plane.boole = 500;
plane.attackLeve = 10;
plane.attackLeve = 7;


// 在不支持Object.create方法的浏览器中也可以通过以下方法实现对象的克隆
Object.create = Object.create || function(obj) {
	var F = function() {} // 创建构造函数
	F.prototype = obj;
	return new F(); // F实力对象的__proto__ === F.prototype
}

// Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
var clonePlone = Object.create(plane);

console.log(clonePlone);

构造函数

js的函数既可以作为普通函数被调用,也可以作为构造器被调用。当使用new运算符来调用函数时,此时的函数就是一个构造器。我们来简单看下如何用new运算符从构造器中得到一个对象。

function Preson (name) {
    this.name = name;
}
Preson.prototype.sayName = function() {
    console.log(this.name);
}
var p = new Preson('sven');
p.sayName(); // sven
console.log(Object.getPrototypeOf(p) === Preson.prototype) // true

上边的代码,我们会时常用到。运算符来创建对象的过程,实际上也是克隆了Object.prototype对象,然后进行了一些其他的操作。

new关键字实现

function my_new() {
    var constructor = [].shift.call(arguments);
    // constructor.prototype克隆一个新对象。
    var context = Object.create(constructor.prototype);
   	// 借用外部传入的构造器给context设置属性。
    var result = constructor.apply(context, arguments);
    // 确保构造器总会有一个返回值
    return typeof result === 'object' ? result: context;
}
var new_p = my_new(Preson, 'zhang');
new_p.sayName();