JavaScript 原型

来源:互联网 发布:数据有效性wps2016 编辑:程序博客网 时间:2024/06/07 08:01

原型

1.原型的含义:
在JavaScript中,函数是一个包含属性和方法的Function对象。而原型(prototype)就是Function类型对象的一个属性。
在函数定义是就包含了prototype属性,他的初始值是空对象。在JavaScript中并没有定义函数的原始类型,所以原型是任何类型。原型是用于保存对象的共享属性和方法的,原型的属性和方法并不会影响函数本身的属性和方法。

相关代码:function fn(a,b){    return a+b;}console.log(typeof fn.prototype);//object

2、获取原型
获取原型的方法有两种,可以设置共享额属性和方法

通过构造函数的prototype属性

相关代码:function Hero(){    console.log("this is text");}console.log(Hero.prototype);结果:输出一个空对象:Hero{}

通过Object对象的getPrototypeOf(obj)方法。

相关代码:function Hero(){    console.log("this is text");}console.log(Object.getPrototypeOf(Hero));结果:[Function]

原型的属性和方法
通过如下两种方式设置原型的属性和方法

1、原型的属性和方法可以单独定义

构造函数.prototy.属性名=属性值;
构造函数.prototy.方法名=function(){}

相关代码:function Hero() {    this.name="gzl";    this.sayYou=function () {        console.log('this is g');    }}var hero=new Hero();console.log(hero.name);hero.sayYou();console.log(Hero.prototype);Hero.prototype.age=23;Hero.prototype.sayMe=function () {    console.log('this is z');}console.log(Hero.prototype.age);Hero.prototype.sayMe();结果:gzlthis is gHero {}23this is z

2、直接为原型定义一个新对象

构造函数.prototype={
属性名:属性值;
方法名:function(){ }
}

相关代码:function Hero(){    this.name='gzl';    this.sayMe=function(){        console.log('this is g');    }}var hero=new Hero();console.log(hero.name);hero.sayMe();console.log(Hero.prototype);Hero.prototype={    age:25,    sayYou:function(){        console.log('this is z');    },}console.log(Hero.prototype.age);Hero.prototype.sayYou();结果:gzlthis is gHero {}25this is z

_proto_属性

相关代码:function Hero(){}Hero.prototype = {    name : "Mary",    salary : 3800,    sayYou:function () {        console.log('this is gzl');    }}var hero = new Hero();console.log( hero.name );// Maryhero.sayYou();//this is gzl

值得注意的是: -proto-属性与 prototype 属性并不等价-proto-属性是指定对象的属性。prototype 属性是指定构造函数的属性。再有就是,-proto-属性只能在学习或调试的时候使用。

原型链

构造函数或构造器具有 prototype 属性,对象具有 proto 属性,这就是之前学习的原型。 如果构造函数或对象 A ,A 的原型指向构造函数或对象 B,B 的原型再指向构造函数或对象 C,以此类推,最终的构造函数或对象的原型指向 Object 的原型。由此形成一条链状结构,被称之为原型链。 按照上述的描述,在 B 中定义的属性或方法,可以直接在 A 中使用并不需要定义。这就是继承,它允许每个对象来访问其原型链上的任何属性或方法。 原型链是 ECMAScript 标准中指定的默认实现继承的方式。

相关代码:function A() {    this.a='a';}var a=new A();console.log(a.a);//aconsole.log(a.b);//undefinedfunction B() {    this.b='b';}B.prototype=a;var b=new B();console.log(b.b);//bconsole.log(b.a);//afunction C() {    this.c='c';}C.prototype=a;C.prototype=b;var c=new C();console.log(c.c);//cconsole.log(c.b);//bconsole.log(c.a);//a
原创粉丝点击