javascript中对原型的理解

来源:互联网 发布:js请求servlet 编辑:程序博客网 时间:2024/06/06 04:12

1.什么是原型

在构造函数创建出来的时候,系统会默认的帮构造函数创建并关联一个神秘的对象,这个对象就是原型,原型默认的是一个空的对象。

2.原型的作用

原型中的属性和方法,可以被使用该构造函数创建出来的对象所使用。

3.如何访问构造函数中的原型

构造函数.prototype

4.如何给原型对象添加属性和方法

使用对象的动态特性

5.原型链

对象的原型指向原型对象,形成原型链

代码:
constructor: 原型对象内的一个属性,指向该原型对象相关联的构造函数
__proto__:原型对象对象中的属性,可以使用 对象.proto 去访问原型对象

    <script>        // 动物 --》 人 --》老师 --》坏老师        function Animal(){            this.gender = "male";        }        Human.prototype = new Animal();        Human.prototype.constructor = Human;        function Human(){            this.actionWay = "走路";        }        Teacher.prototype = new Human();        Teacher.prototype.constructor = Teacher;        function Teacher(){            this.skill = "教书";        }        BadTeacher.prototype = new Teacher();        BadTeacher.prototype.constructor = BadTeacher;        function BadTeacher(){            this.name = "chris";        }        var t = new BadTeacher();        console.log(t);        console.log(t.__proto__);        console.log(t.__proto__.__proto__);        console.log(t.__proto__.__proto__.__proto__);        console.log(t.__proto__.__proto__.__proto__.__proto__); // object        console.log(t.__proto__.__proto__.__proto__.__proto__.__proto__); // 对象的原型还是一个对象 所以是Object 不是null        console.log(t.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__); // null    </script>

结果:
这里写图片描述
总结:

当使用对象去访问属性和方法的时候,会首先在对象自己内部进行查找,如果找到了,就直接使用。如果没有找到,就去原型中查找,查找到之后,使用。如果原型中还没有, 如果是属性,就是undefined,如果是方法,就报错。

// 定义构造函数   function Person(name, status) {            this.name = name;            this.status = status;            this.act = function () {                console.log("演戏");            };            this.exercise = function () {                console.log("就不强身健体,就要保卫祖国");            }        }        // 初始化 创建构造函数    var p = new Person("xyz","single");    // 添加原型方法    Person.prototype.exercise = function () {            console.log("强身健体,保卫祖国");        }// 该构造函数创建出来的对象访问原型方法   p.exercise();  console.log(Person.prototype); // Object  console.log(p.prototype);  // undefined
0 0
原创粉丝点击