首先我们继续上文的代码,我们来把这段代码延伸一下:

    <script type="text/javascript">
        var Person = function (name, age) {
            this.name = name;
            this.age = age;
            this.Introduce = function () {
                alert("My name is " + this.name + ".I'm " + this.age);
            };
        };
        var person1 = new Person("飞林沙", 21);
        var person2 = new Person("kym", 26);
        alert(person1.Introduce == person2.Introduce);
    </script>

结果弹出false。也就是说,这两个对象的方法是不同的方法。那么我们知道,在C#中,每个对象会维护着一个方法表,可是方法表应该指向同一块地址。如果是这样的话,那当我们声明了100个对象,是不是要建立100个对象拷贝,对空间是不是一个很大的浪费呢?

于是我们就想了这样的解决办法,用prototype:

    <script type="text/javascript">
        var Person = function (name, age) {
            this.name = name;
            this.age = age;
        };
        Person.prototype.Introduce = function () {
            alert("My name is " + this.name + ".I'm " + this.age);
        }
        var person1 = new Person("飞林沙", 21);
        var person2 = new Person("kym", 26);
        alert(person1.Introduce == person2.Introduce);
    </script>

这样就可以了。所以你还会再说是否用prototype都是一样的么?其实我以前也是这么理解的,在这次偶然的试验中看到了这个问题。

 

相关文章:

  • 2021-11-29
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-04-08
  • 2021-08-18
  • 2021-10-07
  • 2021-09-20
猜你喜欢
  • 2022-12-23
  • 2021-08-28
  • 2021-11-26
  • 2022-01-11
  • 2021-09-16
  • 2021-08-27
  • 2021-09-10
相关资源
相似解决方案