標籤:height 修改 oct function class 方法 pre struct instance
原型鏈一.建構函式與原型鏈的關係
部落格中:http://www.cnblogs.com/shuiyi/p/5305435.html
的圖
例子:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script> 7 function Person(obj) { 8 this.obj = obj || {} 9 this.name = this.obj.name || "匿名";10 this.age = this.obj.age || 18;11 this.sex = this.obj.sex || "男";12 }13 14 Person.prototype.fn = function () {15 console.log("我是掛載在原型鏈上的函數");16 }17 var p1 = new Person({18 name:"小明"19 });20 // console.log(p1.__proto__.sayHi === p1.sayHi);// ture21 console.log("建構函式");22 console.dir(Person);23 console.log("執行個體化後的對象");24 console.dir(p1);25 console.log(Person.prototype === p1.__proto__); // true26 console.log(Person instanceof Object); //true27 28 </script>29 </head>30 <body>31 32 </body>33 </html>
Person.prototype === p1.__proto__ 以及Person instanceof Object是true的原因:
二.原型指向
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script> // 萬物皆對象 function Person(name,age) { this.name = name || "名字"; this.age = age ||18; } function Stuent(number) {// this.name = name;// this.age =age; this.number = number; } // 修改指向方法一:推薦 Stuent.prototype = new Person();// var stu1 = new Stuent("一號"); // 修改指向方法二:// Stuent.prototype = {// constructor:Person,// age:11// }; console.dir(Stuent);// console.dir(stu1.age); </script></head><body></body></html>三.JS內建對象的原型鏈
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <script> 6 // new Object(); 7 // new Number(); 8 // new String(); 9 // new Boolean();10 // new Function();11 // new Date();12 13 // var obj1 = new Object();14 // var obj2 = {};15 // console.dir(obj1);16 // console.dir(obj2);17 //18 // console.log(obj1 instanceof Object); // true19 // console.log(obj2 instanceof Object); // true20 21 var data1 = new Number("123");22 console.dir(data1);23 console.log(data1.__proto__); // Number24 console.log(data1.__proto__.__proto__); // Object25 console.log(data1.__proto__.__proto__.__proto__); // null26 console.log(data1.__proto__.__proto__ === data1.__proto__.__proto__); // ture27 // console.dir(typeof data1.toString()); //"123" string28 29 var data2 = true;30 // console.log(data2.toString()); // "true"31 32 </script>33 <title>Title</title>34 </head>35 <body>36 37 </body>38 </html>
JavaScript--原型鏈