您的位置:首页 > Web前端 > JavaScript

js原型、constructor、继承总结

2017-04-08 10:01 260 查看
原型:函数创建时会自动內建一个prototype属性,这个属性是一个object,所以也称该属性称为原型对象。

代码:

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


输出结果:

function Fun()

arguments:null

caller:null

length:0

name:"Fun"

prototype:Object

__proto__:function ()

[[FunctionLocation]]:index.html:105

[[Scopes]]:Scopes[1]

输出prototype对象;

代码:

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


结果:

Object

constructor:function Fun()

__proto__:Object

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

console.dir( Fun.prototype.constructor );


function Fun()

arguments:null

caller:null

length:0

name:"Fun"

prototype:Object

__proto__:function ()

[[FunctionLocation]]:index.html:105

[[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__ );


Object

constructor:function Object()

hasOwnProperty:function hasOwnProperty()

isPrototypeOf:function isPrototypeOf()

propertyIsEnumerable:function propertyIsEnumerable()

toLocaleString:function toLocaleString()

toString:function toString()

valueOf:function valueOf()

__defineGetter__:function __defineGetter__()

__defineSetter__:function __defineSetter__()

__lookupGetter__:function __lookupGetter__()

__lookupSetter__:function __lookupSetter__()

get __proto__:function __proto__()

set __proto__:function __proto__()

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

来new一个对象:

var fun = new Fun();
console.dir( fun.__proto__ );

输出结果:

Object

setName:function (
name )

arguments:null

caller:null

length:1

name:""

prototype:Object

__proto__:function ()

[[FunctionLocation]]:index.html:111

[[Scopes]]:Scopes[1]

constructor:function Fun()

__proto__:Object

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

这里说下关于new 关键字的一些特性,在之前我曾想过new 这个操作过程是什么,但是奈何没有找到相关资料,最近在看《JavaScript设计模式与开发实践》一书的时候,有描述关于new 关键字,解释是说new 的时候会将所new的构造函数返回一个对象,所以会说new一个对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: