Javascript学习笔记 What is "extend"
1. 从关于“new”的一段代码开始
从《JavaScript语言精粹》上看到一个关于“new”实现方法的猜测,实现正规,而且符合实际情况。下面把代码列下来。
Function.method('new', function(){ // 创建一个新对象,它继承自构造器函数的原型对象。 var that = Object.create(this.prototype); // 调用构造器函数,绑定 -this- 到新对象上。 var other = this.apply(that, arguments); // 如果它的返回值不是一个对象,就返回该新对象。 return (typeof other === 'object' && other) || other;});
var Parent = function(x) { this.x = x + 1;};Parent.prototype.getX = function() { return this.x;};
var Child = function() { //此构造函数的实现下面会讨论};Child.prototype = new Parent();
var p = new Parent();var c = new Child();
var Child = function(x, y){ //$1:下面三行实现如Java中的this.parent()方法 this.method = Parent; this.method(x); delete this.method; //Child自己的构造方法中的内容。 this.y = y;};
Parent.call(this, x);//或Parent.apply(this, new Array(x));
var Child = function(x, y) { Parent.call(this, x); this.y = y;};Child.prototype = new Parent();Child.prototype.getY = function() { return this.y;}
console.log(Child.prototype.constructor === Parent); //trueconsole.log(typeof Parent == "function"); //trueconsole.log(typeof Child == "function"); //true