ES6-class类、继承、this指向

<button type="button">我是输出son1的第一个参数</button>
    <script>
        class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                return this.x + this.y;
            }
        }
		var that;
        class Son extends Father {
			// constructor里面的this指向的是创建的实例对象
            constructor(x, y) {
                super(x, y);
                this.x = x;
                this.y = y;
				this.btn = document.querySelector('button');
				this.btn.onclick = this.output;   //这里不需要加小括号
				that = this;   // 将constructor的this传递给全局变量that
            }
				sub(){
				// 普通函数里面的this指向的是创建的实例对象
					return this.x - this.y;
				}
				output(){
					// output里面的this指向的是btn,因为是btn调用了这个方法
					console.log(this);    // 输出:<button type="button">我是输出son1的第一个参数</button>
					console.log(this.x);  // btn里面没有x这个属性,所以输出undefined
					console.log(that.x);  // 通过设置一个全局变量that,将constructor的this传递给了that,再输出that.x,所以点击按钮输出5
			}
						
        }
		var son1 = new Son(5,6);
		console.log(son1.sum());
		console.log(son1.sub());

输出:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值