您的位置:首页 > 编程语言 > Java开发

javascritp学习笔记之理解构造器Function.prototype

2016-01-22 14:50 603 查看
前言:

本文逻辑稍显混乱,因为当时是自己想来理解这部分概念,调试环境是Google Chrome。

而且这也只是浅显的探讨。

很多知识点,请参考《javascript权威指南》

先说prototype

其实就相当于Function有属性、方法



如图,有方法apply()、call()、属性arguments……

当定义了

Function.prototype.construct之后



Function.prototype就多了一种方法construct

//使用apply来链接构造器
Function.prototype.construct=function(aArgs){
var oNew=Object.create(this.prototype)
this.apply(oNew,aArgs)
return oNew
}


//为Function定义一个构造器函数construct(),就像是Function本来带有的call()、apply()一样
function Myconstructor(){
for(var nProp=0;nProp<arguments.length;nProp++){
this["property"+nProp]=arguments[nProp]
}
}
var myArray=[4,"hello world",false]
var myInstance=Myconstructor.construct(myArray)  //传入myArray,因为myArray长度不确定,所以用apply
console.log(myInstance.property1)


再说构造函数

function Range(from,to){
this.from=from
this.to=to
console.log("this"+this)
}//相当于重新继承了range,使其具备methods方法吗?
//定义methods
Range.prototype={
includes:function(x){
return this.from<x && x<=this.to
},
foreach:function(f){
for(var x=Math.ceil(this.from);x<this.to;x++) f(x)
},
toString:function(){
return "("+this.from+"....."+this.to+")"
}
}


Range是一个对象Object,继承了Object的方法和属性,同时我们又定义了Range.prototype新的方法includes、foreach、tostring



新定义Range的对象r,它是Range的实例化对象,具有属性from:1,to:3,以及Range的方法foreach,includes,toString以及Object属性



实例化对象r的construtor是function Object()

构造函数Range的constructor是function Function()

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: