JS对象模型

要创建 Point 的新实例,必须使用 new 操作符。以这种方式调用构造函数实际上会经历以下 4
个步骤:
(1) 创建一个新对象;
(2) 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象) ;
(3) 执行构造函数中的代码(为这个新对象添加属性) ;
(4) 返回新对象。

老语法

function Point (x,y) {
    // console.log('Point init~~~');
    this.x = x;
    this.y = y;
}

// var a = new Point(4,5);  #实例化必须带new
// console.log(a)

function Point123(x,y,z){
    // console.log('Point123 init~~~')
    Point.call(this,x,y);  //借助call注入this
    this.z = z
}

// console.log(Point123)
var b = new Point123(10,11,12)
console.log(b)

新语法

继承

class Point{
    constructor(x,y){
        console.log('Point init~~~')
        this.x = x
        this.y = y
        this.show = () => console.log(this.x, this.y)
    }
    show () {
        console.log(this.x, this.y);
        // return this.x,this.y;
    }
}

// let p1 = new Point(1,2);
// console.log(p1)



class Point123 extends Point{
    constructor(x,y,z){
        super(x,y);
        this.z = z
        this.show = () => console.log(this.x,this.y,this.z)
        console.log('Point123~~~')
    }
    show (x){
        // super.show()
        console.log(super.show(),this.z)
        
    }
}


let p2 = new Point123(10,11,12);
console.log(p2)
p2.show()

静态方法

class Point{
    constructor(x,y){
        console.log('Point init~~~')
        this.x = x
        this.y = y
        // this.show = () => console.log(this.x, this.y)
    }
    //静态的,就是类的 
    static show (x,y) {  // 等效为Python中的classmethod
        // console.log(this.x, this.y); ;类方法就不能用实例调用了
        console.log(x,y)  //可以这样调用
        console.log(typeof this,'~~~~~~~~~')
        // return this.x,this.y;
    }
}

let p1 = new Point(1,2);
console.log(p1)
//p1.show()   不能用实例调用
Point.show(3,4)
p1.constructor.show(5,6)  //这样可以

解决this问题

var obj = {
    name:100,
    getName:function () {
        console.log(this.name,'in obj+++++')
        return function (x, y) {  //改成箭头函数就没this的问题了,但是老版本有可能没用箭头函数
            // console.log(this)
            console.log(this.name,x,y)  //这个this是全局跟obj实例没关系
        }
    }
}

anormalfunc = obj.getName()
// anormalfunc.call(obj,...[1,2])  //把obj给this
// anormalfunc.apply(obj,[3,33])

anormalfunc.bind(obj)
console.log(anormalfunc.bind(obj))

obj.getName().bind(obj)(1,3)

改成箭头函数可以直接调用obj,getName()
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值