日期:2014-05-16 浏览次数:20453 次
Function.prototype.__new__ = function(){
	var emptyFunction = function(){};
	emptyFunction.prototype = this.prototype;
	var newObject = new emptyFunction();
	newObject.__proto__ = this.prototype;
	newObject.constructor = this.prototype.constructor;
	var returnedObject = this.apply(newObject, arguments);
	return (typeof returnedObject === 'object' && returnedObject) || newObject;
};
function Person(name){
	this.name = name;
}
Person.prototype = {
	getName:function(){
		return this.name;
	}
}
var p = new Person("a");
alert(p.constructor === Person); //false
alert(p.constructor === Object); //true 从第4行看到Person.prototype.constructor === Object 即Person.prototype = new Object(); Person.prototype.getName = function(){..}
function Person(name,age){
	this.name = name;
	this.age = age;
	this.getAge = function(){//特权方法(privileged methods) 避免其被子类继承
		return this.age
	}
}
Person.prototype.getName = function(){ //原型方法 需要被其子类集成 
	return this.name;
}//BTW: 通过这种方式为Person扩充原型方法,没有通过"="操作符为Person.prototype赋予新的对象(= new Objecct) 所以Person.prototype.constructor没有出现混乱.
function Singleton(){
	if(Singleton.inst){
		return Singleton.inst;
	}
	Singleton.inst = this;
}
var s1 = new Singleton();
var s2 = new Singleton();
alert(s1===s2);//true
function Singleton(){
	if(this instanceof arguments.callee){ //如果没有通过new进入函数体,这里的this会指向window
		return new arguments.callee;
	}
	if(Singleton.inst){
		return Singleton.inst;
	}
	Singleton.inst = this;
}
var s1 = new Singleton();
var s2 = Singleton();
alert(s1===s2);//true