原型和原型链

代码块一

$(function() {
    function Dog(){
    }
    var d = new Dog();
    console.log(d.__proto__);
    console.log(Dog.prototype);
}

可以发现d.__proto__和Dog.prototype指向的是同一个原型对象
一个对象由一个函数实例化出来,则该对象和该函数指向的是同一个原型对象

  • 示例图

在这里插入图片描述

代码块二

自定义一个原型对象

$(function() {
    function Dog(){
    }
    Dog.prototype = {
        constructor:Dog,
        init:function () {
            this.name = 'wc';
            this.age = 1;
        },
        say:function(){
            console.log(this.name,this.age); //wc 1
        }
    }
    var d = new Dog();
    d.init();
    d.say();

如何在不调用init()的情况下也能够使用name和age

$(function() {
    function Dog(){
        return new Dog.prototype.init();
    }
    Dog.prototype = {
        constructor:Dog,
        init:function () {
            this.name = 'wc';
            this.age = 1;
        },
        say:function(){
            console.log(this.name,this.age);
        }
    }
    var d = new Dog();
    d.say();
 }

报错: d.say is not a function TypeError: d.say is not a function 原因如下
在这里插入图片描述
解决办法:把init函数的原型对象改为Dog函数的原型对象。

最终版

$(function() {
    function Dog(){
        return new Dog.prototype.init();
    }
    Dog.prototype = {
        constructor:Dog,
        init:function () {
            this.name = 'wc';
            this.age = 1;
        },
        say:function(){
            console.log(this.name,this.age);
        }
    }
    Dog.prototype.init.prototype = Dog.prototype;
    window.Player = Player;
    var d = new Dog();;
    d.say();
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值