js的构造函数和原型

1.构造函数创建对象

 function Person(name,age,job) {
            this.name = name;
            this.age = age;
            this.job = job;  
            this.sayName = function () {
                alert(this.name);
            }
        }
        var person1 = new Person("cherry", 25, "Engineer");
        person1.sayName();

2.原型

  function Person(name, age, job) {

            this.name = name;
            this.age = age;
            this.job = job;
        }
        Person.prototype.sayName = function () {
            alert(this.name);
        }
        var person1 = new Person("cherry", 25, "Engineer");
        person1.sayName();

3.继承

  function Person(name, age, job) {
            this.name = name;
            this.age = age;
            this.job = job;
        }
        Person.prototype.sayName = function () {
            alert(this.name);
        }
        function Chinese() {
        }
        Chinese.prototype = new Person("cherry", 25, "Egineer");//Chinese继承自Person
        var chinese = new Chinese();
        chinese.sayName();//chinese共享Person的function
posted @ 2020-04-26 22:23  小新的开始  阅读(110)  评论(0编辑  收藏  举报