JavaScript USES constructors and prototypes to simulate the functionality of c-sharp classes

  • 2020-03-30 02:14:55
  • OfStack


       //The constructor
        function person(name, age) {
            this.name = name;
            this.age = age;
        }
        //Define the person stereotype, and the properties in the stereotype can be referenced by the custom object
        person.prototype = {
            getName: function () {
                return this.name;
            },
            getAge: function () {
                return this.age;
            }
        }


 So there's another concept that needs to be introduced  -  Prototype ( prototype ), we can simply prototype As a template, the newly created custom object is the template ( prototype )   It's not actually a copy, it's a link, but it's invisible, it feels like a copy. 
JavaScript The function of the class is simulated by means of constructor and prototype.  
       window.onload = function () {
            person.prototype.sex = ' male ';
            var fmj =new person('kkk', 22);
            alert(' First output :'+fmj.sex);
            fmj.sex = ' A secret ';
            alert(' Second output :' + fmj.sex);
            delete fmj.sex;
            alert(' Third output :' + fmj.sex);
            //Output in the debug console.
            //console.log(fmj.getAge());
            }


Related articles: