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

作为一个前端初学者,从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方法
//定义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()
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值