您现在的位置:首页 >> 前端 >> 内容

javascript学习笔记六:prototype的提出

时间:2018/7/10 14:04:30 点击:

  核心提示:系列文章导航:网页运行原理关于响应事件Ajax入门  首先我们继续上文的代码,我们来把这段代码延伸一下:script type='text/var Person = function (name, a...

系列文章导航:

javascript学习笔记一——数据类型

javascript学习笔记二——函数

javascript学习笔记三——作用域

javascript学习笔记四——Eval函数

javascript学习笔记五——类和对象

javascript学习笔记六:prototype的提出

javascript学习笔记七——原型链的原理

javascript学习笔记八——用JSON做原型

javascript学习笔记九——prototype封装继承

javascript学习笔记十——网页运行原理

javascript学习笔记十一——包装DOM对象

javascript学习笔记十三——关于响应事件

javascript学习笔记十二——Ajax入门


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

    <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都是一样的么?其实我以前也是这么理解的,在这次偶然的试验中看到了这个问题。

Tags:10 06 6A AV 
作者:飞林沙 来源:博客园