JavaScript 原型

原型

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();

结果:
gzl
this is g
Hero {}
23
this 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();

结果:
gzl
this is g
Hero {}
25
this 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 );// Mary
hero.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);//a
console.log(a.b);//undefined

function B() {
    this.b='b';
}
B.prototype=a;
var b=new B();

console.log(b.b);//b
console.log(b.a);//a

function C() {
    this.c='c';
}

C.prototype=a;
C.prototype=b;
var c=new C();
console.log(c.c);//c
console.log(c.b);//b
console.log(c.a);//a
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值