原型的方法,在构造其中调用

来源: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回答

好帮手慕久久

2021-04-21

同学你好,是说如下位置吗?

http://img.mukewang.com/climg/607f9ffc097cf9a206180273.jpg

如果是的话,那么上图中的写法是正确的。

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

http://img.mukewang.com/climg/607fa0a409c538b806400268.jpg

http://img.mukewang.com/climg/607fa0c60928292407000393.jpg

这是合理的,也是可以的。

如果不是这里,可以具体说明一下,最好举个例子,老师再为你解答。

祝学习愉快!

0

0 学习 · 15276 问题

查看课程