How do you understand this object? How do you write this?

//
        function Word(words){
            this.words = words;
        }
        Word.prototype = {
            alert(){
                alert(this.words);
            }
        }
        //
        var w = new Word("hello world");
        w.print = function(){
            console.log(this.words);
            console.log(this);  //Person
        }
        w.print();  //hello world
        w.alert();  //hello world

{

        alert(){
            alert(this.words);
        }
    }
    
Jun.15,2022

this is how to write es6, which is equivalent to:

 

prototype object

when you use obj.xxx to access the properties of an object, the JavaScript engine first looks for the property on the current object. If it cannot find it, it looks for it on the prototype object. If it is not found yet, it goes all the way to the Object.prototype object. Finally, if it has not been found yet, it can only return undefined.

Menu