js原型、constructor、继承总结

原型:函数创建时会自动內建一个prototype属性,这个属性是一个object,所以也称该属性称为原型对象。

代码:

function Fun(){
    this.name = 'sven';
    this.getName = function(){
        alert( this.name );
    }
}
console.dir( Fun );

  1. 输出结果:
  2. function Fun()
    1. arguments:null
    2. caller:null
    3. length:0
    4. name:"Fun"
    5. prototype:Object
    6. __proto__:function ()
    7. [[FunctionLocation]]:index.html:105
    8. [[Scopes]]:Scopes[1]

输出prototype对象;

代码:

function Fun(){
    this.name = 'sven';
    this.getName = function(){
        alert( this.name );
    }
}
console.dir( Fun.prototype );

结果:

  1. Object
    1. constructor:function Fun()
    2. __proto__:Object

在prototype中也有个construct属性,我们输出一下:

console.dir( Fun.prototype.constructor );
  1. function Fun()
    1. arguments:null
    2. caller:null
    3. length:0
    4. name:"Fun"
    5. prototype:Object
    6. __proto__:function ()
    7. [[FunctionLocation]]:index.html:105
    8. [[Scopes]]:Scopes[1]

当我看到内部也有个prototype的时候我在想Fun.prototype.constructor.prototype == Fun.prototype;输出的结果是true,那么可以得出Fun.prototype.constructor ==  Fun;这些结果就是为了告诉我Fun是个构造函数?,在高程中有这么一种说法,说函数名只是一个指针,那么可以从中看出Fun指向的是它自身的构造函数。那么Fun.prototype.constructor.prototype == Fun.prototype得出true就不矛盾了,可以得出一个结论原型对象其实是构造函数内部的一个属性。

继承:关于继承,js中继承是通过原型的方式继承的,在原型中有个属性__proto__,这个属性称为原型链,

console.dir( Fun.prototype.__proto__ );
  1. Object
    1. constructor:function Object()
    2. hasOwnProperty:function hasOwnProperty()
    3. isPrototypeOf:function isPrototypeOf()
    4. propertyIsEnumerable:function propertyIsEnumerable()
    5. toLocaleString:function toLocaleString()
    6. toString:function toString()
    7. valueOf:function valueOf()
    8. __defineGetter__:function __defineGetter__()
    9. __defineSetter__:function __defineSetter__()
    10. __lookupGetter__:function __lookupGetter__()
    11. __lookupSetter__:function __lookupSetter__()
    12. get __proto__:function __proto__()
    13. set __proto__:function __proto__()

从输出结果我们可以看到Fun.prototype.__proto__指向的是function对象。

来new一个对象:

var fun = new Fun();
console.dir( fun.__proto__ );
输出结果:

  1. Object
    1. setName:function ( name )
      1. arguments:null
      2. caller:null
      3. length:1
      4. name:""
      5. prototype:Object
      6. __proto__:function ()
      7. [[FunctionLocation]]:index.html:111
      8. [[Scopes]]:Scopes[1]
    2. constructor:function Fun()
    3. __proto__:Object

这种结构形式和Fun,prototype很像,fun.__proto__ == Fun.prototype 得出的是true;

这里说下关于new 关键字的一些特性,在之前我曾想过new 这个操作过程是什么,但是奈何没有找到相关资料,最近在看《JavaScript设计模式与开发实践》一书的时候,有描述关于new 关键字,解释是说new 的时候会将所new的构造函数返回一个对象,所以会说new一个对象。



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值