体现对象原型分步式写法javascript
//原型分步式写法 //构造函数 function Person(){} //对象原型 Person.prototype.name = 'Avensatr'; Person.prototype.age = '22'; Person.prototype.job = 'Software Engineer'; Person.prototype.sayName = function(){ console.log(this.name); }
我问你答?? 打印结果是??html
var person = new Person(); //__proto__隐式原型与显式原型Person.prototype console.log(person.__proto__); console.log(Person.prototype); //构造函数(对象原型构造用于构造对象) console.log(Person.prototype.constructor); console.log(Person.prototype.constructor === Person); //构造函数原型 console.log(Person.prototype.constructor.prototype); //对象原型 console.log(Person.prototype.__proto__); //构造函数是由function Function(){}建立 console.log(Person.prototype.constructor.__proto__); console.log(person.__proto__ === Person.prototype);
理清上述(实例与构造原型对象关联关系)打印结果后,见图解以下前端
完整图解应以下java
Person.prototype只是对象指针引用,真正建立对象的是Person.prototype.constructor.prototype 构造函数原型函数
每一个建立一个函数都有prototype属性,该函数prototype属性指向一个该函数建立的对象.即 Person.prototype.constructor.prototypethis
实例对象之间经过“__proto_隐式原型”与构造函数原型对象“Person.prototype”之间相关联 即person.__proto__ === Person.prototypespa
instanceof 用于检测对象与实例之间关系prototype
person instanceof Person 沿着原型链person.__proto__与Person.prototype查找,若两条线能找到同一个引用,即同一个对象,则返回true,不然返回false设计
体现对象原型封装的写法指针
//原型集中写法 function Person(){} var friends = new Person();//建立一个实例对象 Person.prototype = { name : "Avensatr", age : "22", job : "Software Engineer", sayName : function(){ console.log(this.name); } }
这种面向对象快捷写法 Person.prototype = {} 与上述对象原型分步式写法有所区别;本质体如今原型的重写上
Person.prototype.constrctor 再也不指向 function Person(){} 而指向新的function Object() { [native code] }函数
打印结果以下图
匿名函数自执行封装对象原型方法
function Person(){} Person.prototype = (function () { var setName = function (name) { return name; }, setAge = function (age) { return age; }, setJob = function (job) { return job; }; return { setName : setName, setAge : setAge, setJob : setJob } })();
匿名函数自执行与体现对象原型封装的写法原理是同样的,这里再也不赘述
【资料参考】
http://www.sxrczx.com/docs/js/2305453.html
JavaScript高级程序设计(第三版)