原型的方法,在构造其中调用
来源:7-1 包装类
曼曼前端
2021-04-21 11:30:34
对象实例调用原型的方法,可以写在构造器中吗
function TrafficLight() {
// 颜色属性,一开始都是红色
// 红色1、黄色2、绿色3
this.color = 1;
// 调用自己的初始化方法
this.init();
// 绑定监听
this.bindEvent();
}
// 初始化方法
TrafficLight.prototype.init = function() {
// 创建自己的DOM
this.dom = document.createElement('img');
// 设置src属性
this.dom.src = 'images/' + this.color + '.jpg';
box.appendChild(this.dom);
};
// 绑定监听
TrafficLight.prototype.bindEvent = function() {
// 备份上下文,这里的this指的是JS的实例
var self = this;
// 当自己的dom被点击的时候
this.dom.onclick = function () {
// 当被点击的时候,调用自己的changeColor方法
self.changeColor();
};
}
// 改变颜色
TrafficLight.prototype.changeColor = function () {
// 改变自己的color属性,从而有一种“自治”的感觉,自己管理自己,不干扰别的红绿灯
this.color ++;
if (this.color == 4) {
this.color = 1;
}
// 光color属性变化没有用,还要更改自己的dom的src属性
this.dom.src = 'images/' + this.color + '.jpg';
};
1回答
同学你好,是说如下位置吗?

如果是的话,那么上图中的写法是正确的。
以this.bindEvent()为例,this指向的是实例对象,bindEvent是原型上的方法,TrafficLight是构造函数(构造器)。this.bindEvent()写在TrafficLight中,会在实例化TrafficLight时,就执行:


这是合理的,也是可以的。
如果不是这里,可以具体说明一下,最好举个例子,老师再为你解答。
祝学习愉快!
相似问题