What's wrong with this code?

 <script>
        $(document).ready(function () {
            var box = $("-sharpbox1");

            function changeColor(color) {
                this.color = color;
            }

            changeColor.prototype.chanCol = function (obj) {
                var color = this.color; //
                obj.on("click",function () {
                    $(this).css("background-color",color);
                });
            }

            var ch = new changeColor("red");
            ch.chanCol(box);
        });
    </script>

when I refer to this.color directly in the sentence $(this) .css ("background-color", this.color) , the color of box does not change, but after assigning the value of this.color to color, I can change it by writing color, box value in css (). Why can"t I write this.color?

directly?

just thought about it, is it the relationship of the scope chain?

Aug.20,2021

this is the scope problem of this. The this in the event handler no longer points to the ch object, but to the current event object, so you need to define a global variable outside the event handler to cache this


.

the this in this function refers to the dom element (obj)

.
obj.on("click",function () {
    $(this).css("background-color",color);
});

when you write $(this) .css ("background-color", this.color) , you mean assigning the color attribute of the dom element . Of course it's undefined .

var color = this.color; //

this this points to the function changeColor , that is, the object ch

.
$(document).ready(function () {
    var box = $("-sharpbox1");

    function changeColor(color) {
        this.color = color;
    }

    changeColor.prototype.chanCol = function (obj) {
        var that = this;
        var color = that.color; //
        obj.on("click",function () {
            $(that).css("background-color",color);
        });
    }

    var ch = new changeColor("red");
    ch.chanCol(box);
});
Menu