一段代码:
var controller = {
notify: function(obj){
obj.notify();
}
}
var base_obj = {
notify: function(){
alert('base');
}
}
function f(){
f.prototype = base_obj; //注意这句
this.notify = function(){
alert('sub');
}
}
var sub_obj = new f();
controller.notify(base_obj);
controller.notify(sub_obj);
console.log(sub_obj.constructor === base_obj.constructor); //false
console.log(base_obj.constructor === Object); //true;
console.log(sub_obj.constructor === f); //true
console.log(sub_obj.__proto__ === base_obj) //false
-->月影的有关js new的范式:
function f(){
this.a = 1;
this.b = "str";
}
var c = new f;
<==>
var d = g(){};
g.prototype = f.prototype;
var h = new g();
f.call(h);
因此这段:
function f(a){
f.prototype = baseObj; //注意new这个过程的范式表达过程的顺序;
this.x =a;
}
new的语义上实现的过程是 - Constructor的执行是在new过程设置prototype对象之后才进行的;因此
subObj对象的__proto__其实引用着还是老的,原有的function f的prototype对象;而在第一次new之后
才f的prototype才被设为baseObj;
e.g.: 单根实例的实现可以是:
function f(){
f = null;
this.x = 10;
}
var d = new f();
try{
var c = new f();
}
catch(e){}