
首先定义一个对象obj,该对象的原型为obj._proto_,我们可以用ES5中的getPrototypeOf这一方法来查询obj的原型,我们通过判断obj的原型是否与Object.prototype相等来证明是否存在obj的原型,答案返回true,所以存在。然后我们定义一个函数foo(),任何一个函数都有它的prototype对象,即函数的原型,我们可以在函数的原型上添加任意属性,之后通过new一个实例化的对象可以共享其属性(下面的两个例子会详细介绍)。
function foo(){}foo.prototype.z = 3;var obj = new foo();obj.x=1;obj.y=2;obj.x //1obj.y //2obj.z //3typeof obj.toString; //functionobj.valueOf(); // foo {x: 1, y: 2, z: 3}obj.hasOwnProperty("z"); //false
var obj2 = Object.create(null);obj2.valueOf(); //undefinedObject.create()为创建一个空对象,并且此对象的原型指向参数。下面一个综合实例向大家展示一下如何实现一个class来继承另外一个class
//声明一个构造函数Personfunction Person(name,age){this.name = name;this.age = age;}Person.prototype.hi = function (){console.log("Hi,my name is " + this.name +",my age is "+this.age);};Person.prototype.LEGS_NUM=2;Person.prototype.ARMS_NUM=2;Person.prototype.walk = function (){console.log(this.name+" is walking !");};function Student(name,age,classNum){Person.call(this,name,age);this.classNum = classNum;}//创建一个空对象Student.prototype = Object.create(Person.prototype);//constructor指定创建一个对象的函数。Student.prototype.constructor = Student;Student.prototype.hi = function (){console.log("Hi,my name is " + this.name +",my age is "+this.age+" and my class is "+this.classNum);};Student.prototype.learns = function (sub){console.log(this.name+" is learning "+sub);};//实例化一个对象Bosnvar Bosn = new Student("bosn",27,"Class 3");Bosn.hi(); //Hi,my name is bosn,my age is 27 and my class is Class 3Bosn.LEGS_NUM; //2Bosn.walk(); //bosn is walking !Bosn.learns("Math"); //bosn is learning Math
function Person(name,age){this.name = name;this.age = age;}function Student(){}Student.prototype = Person.prototype; //1Student.prototype = Object.create(Person.prototype); //2Student.prototype = new Person(); //3第一种,刚刚在上面已经说过了,直接这样写会让子类和基类同时指向bosn实例;