Javascript学习笔记之类与继承(一)

来源:互联网 发布:淘宝汽车冬季坐垫 编辑:程序博客网 时间:2024/06/07 19:11
作为一个前端初学者,从2015年初入门至今,断断续续已经有一年的时间了。从HTML语法,CSS语法,Javascript慢慢的自己去重构一些网站,渐渐学习心的技术H5以及CSS3。前段时间一直在研究H5制作小游戏,感觉很酷,但是无论H5技术多么炫,最终还是回归javascript的逻辑。因此这一两个月开始深入研究Javascript的语法,把一些心得体会写在这里,也是为了自己来看,不断学习不断进步。

先说构造函数

/*构造函数Complex*/function Range(from,to){    this.from=from    this.to=to    console.log("this"+this)}//我的理解,相当于重新继承了range,使其具备methods方法//定义methodsRange.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()
Function继承自对象Object,类似于Date

再谈继承

function Complex(real,imaginary){    if(isNaN(real)||isNAN(imaginary)){ //isNaN()用于判定是否是非法字符        throw new TypeError()    }    this.r=real    this.i=imaginary}Complex.prototype.add=function(that){    return new Complex(this.r+that.r,this.i+that.i)}Complex.prototype.mul=function(that){    return new Complex(this.r*that.r-this.i*that.i,this.r*that.r+this.i*that.i)}

此时我们可以看到Complex的属性有add,mul,constructor

Complex.prototype={    mag:function(){        return Math.sqrt(this.r*this.r+this.i*this.i)    },    neg:function(){        return new Complex(-this.r,-this.i)    },    toString:function(){        return "{"+this.r+","+this.i+"}"    }}

如果再写上面这行代码

add,mul,constructor消失不见了!!!!!
为什么呢?
Ans:我认为Complex.prototype是重写prototype ,而Complex.prototype.mul是调用Complex.prototype的构造方法constructor

再引到之前的代码:

Function.prototype.construct=function(aArgs){    var oNew=Object.create(this.prototype)    this.apply(oNew,aArgs)    return oNew}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) 

未实例化的对象Myconstructor的constructor是Function,因此可以为Function.prototype定义一个方法construct,可以通过var myInstance=Myconstructor.construct(myArray)实例化对象myInstance

话说回来,Complex.prototype.mul是调用Complex.prototype的构造方法constructor,也就是类似于var myInstance=Myconstructor.construct(myArray)

未完
感觉这里面还是很晦涩难懂

1 0
原创粉丝点击