1. 程式人生 > >JavaScript--原型鏈

JavaScript--原型鏈

doctype .html 構造函數 har www 關系 例子 cnblogs cto

原型鏈

一.構造函數與原型鏈的關系

博客中: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);// ture 21 console.log("構造函數"); 22 console.dir(Person); 23 console.log("實例化後的對象"); 24 console.dir(p1); 25 console.log(Person.prototype === p1.__proto__); //
true 26 console.log(Person instanceof Object); //true 27 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); // true
19         //        console.log(obj2 instanceof Object); // true
20 
21         var data1 = new Number("123");
22         console.dir(data1);
23         console.log(data1.__proto__); // Number
24         console.log(data1.__proto__.__proto__); // Object
25         console.log(data1.__proto__.__proto__.__proto__); // null
26         console.log(data1.__proto__.__proto__ === data1.__proto__.__proto__); // ture
27         //        console.dir(typeof  data1.toString()); //"123" string
28 
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--原型鏈