码迷,mamicode.com
首页 > 其他好文 > 详细

prototype 和 class inherit

时间:2015-10-09 19:56:52      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

function foo created via new Function

 var foo=new Function();					//equals to function foo(){} but the name is ‘‘
 foo.__proto__===Function.prototype		                //true
 var ff=new foo();		   		   	        //equals to new (function foo(){})
 ff.__proto__==foo.prototype				        //true
 var ff2=new (new Function());		  	                //just for test
 ff2.__proto__.__proto__===Object.prototype                     //true

Object.create polyfill

if(typeof Object.create !=‘function‘){
    	Object.prototype.create=function(){
            //use the shared constructor to save memory
            var tmp=function(){};
            
            return function(t){
            //If Type (t) is not Object or Null throw a TypeError exeption.
            if(typeof t!=‘object‘){
             	throw TypeError(‘Object prototype may only be an Object or null‘);
            }
            var obj;
            tmp.prototype=t;
            obj=new tmp();
            tmp.prototype=null;
            return obj;
           }
        }
    }

use Object.create and Prototype to Class Inherit

var Person=function(){
    	this.canWalk=true;
        this.canSwim=true;
        this.canFly=false;
}
Person.prototype.greet=function(){
    	console.log(‘greet someone‘);
}
var Employee=function(name,title){
        Peron.call(this);		                  //use constructor pattern to get the same property
        this.name=name;
        this.title=title;
}
Employee.prototype=Object.create(Person.protoype);
Employee.prototype.constructor=Employee;	          //change the constructor name just habit 
    
//Same result
/*var tmp=new Function();
tmp.prototype=Person.prototype
Employee.prototype=new tmp();			           //grail pattern to avoid the direct connection between Person and Employee
Employee.prototype.constructor=Employee;*/

  

prototype 和 class inherit

标签:

原文地址:http://www.cnblogs.com/thatgeek/p/4864800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!