JS中构造函数的方法定义在原型对象里

构造函数中的方法每当new一个对象的时候,就会创建一个构造函数里的方法,如果多个实例对象就会创建多个方法,占用内存,没有提高代码的复用性;

将方法定义到构造函数的原型对象里,创建多个实例对象而共享一个方法,方法创建了一次。

<script>
        function Persion(name, age) {
            this.name = name;
            this.age = age;
      //在构造函数里定义方法
this.sing = function () { console.log("I can sing"); } } var p1 = new Persion("jack", 12); var p2 = new Persion("tom", 13); console.log(p1.sing === p2.sing);//false


function Persion2(name, age) { this.name = name; this.age = age; }
    //在构造函数的原型对象里定义方法 Persion2.prototype.sing
= function () { console.log("I can sing"); } var p3 = new Persion2("jack", 12); var p4 = new Persion2("tom", 13); p3.sing();//I can sing p4.sing();//I can sing console.log(p3.sing === p4.sing);//true </script>

猜你喜欢

转载自www.cnblogs.com/springa/p/12825664.html
今日推荐