Two construction methods of object-oriented in javascript (constructor) and (the difference between prototype mode)

1. Constructor mode---"alert's result is false

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function Person(name,age,job){
            this.name = name;
            this.age = age;
            this.job = job;
            this.showname = function(){
                alert(this.name);
            }
            
            this.showage = function(){
                alert(this.age);
            }

            this.showjob = function(){
                alert(this.job);
            }
        }
        var tom =  new Person( ' tom ' , 18 , ' programmer ' );
         var jack =  new Person( ' jack ' , 19 , ' sales ' );
        alert(tom.showjob == jack.showjob);  //结果为False
    </script>
</head>
<body>    
</body>
</html>

 2. Prototype mode---->alert result is true

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script>
        function Person(name,age,job){
            this.name = name;
            this.age = age;
            this.job = job;

        }
        Person.prototype.showname = function(){
            alert( ' My name is ' + this .name);
        }
        Person.prototype.showage = function(){
            alert(this.age);
        }
        Person.prototype.showjob = function(){
            alert(this.job);
        }

        var tom =  new Person( ' tom ' , 18 , ' programmer ' );
         var jack =  new Person( ' jack ' , 19 , ' sales ' );
        alert(tom.showjob == jack.showjob);//结果为True       
    </script>
</head>
<body>
    
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325905669&siteId=291194637