首页 > 语言 > JavaScript > 正文

深入了解javascript中的prototype与继承

2024-05-06 14:39:57
字体:
来源:转载
供稿:网友

通常来说,javascript中的对象就是一个指向prototype的指针和一个自身的属性列表。javascript创建对象时采用了写时复制的理念。
只有构造器才具有prototype属性,原型链继承就是创建一个新的指针,指向构造器的prototype属性。
prototype属性之所以特别,是因为javascript时读取属性时的遍历机制决定的。本质上它就是一个普通的指针。

构造器包括:
1.Object
2.Function
3.Array
4.Date
5.String

下面我们来举一些例子吧
代码如下:
<script>
//每个function都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数
//注意Person.constructor 不等于 Person.prototype.constructor. Function实例自带constructor属性
   function Person(name) { 
        this.name = name; 
    }; 
    Person.prototype.getName = function() { 
        return this.name; 
    }; 
    var p = new Person("ZhangSan"); 

    console.log(Person.prototype.constructor === Person); // true 
    console.log(p.constructor === Person);  // true ,这是因为p本身不包含constructor属性,所以这里其实调用的是Person.prototype.constructor    
</script>

我们的目的是要表示
1.表明Person继承自Animal
2. 表明p2是Person的实例

我们修改一下prototype属性的指向,让Person能获取Animal中的prototype属性中的方法。也就是Person继承自Animal(人是野兽)

代码如下:
<script>
   function Person(name) { 
        this.name = name; 
    }; 
    Person.prototype.getName = function() { 
        return this.name; 
    }; 
    var p1 = new Person("ZhangSan"); 

    console.log(p.constructor === Person);  // true 
    console.log(Person.prototype.constructor === Person); // true 

     function Animal(){ }

     Person.prototype = new Animal();//之所以不采用Person.prototype  = Animal.prototype,是因为new 还有其他功能,最后总结。
     var p2 = new Person("ZhangSan");

//(p2 -> Person.prototype -> Animal.prototype, 所以p2.constructor其实就是Animal.prototype.constructor)

     console.log(p2.constructor === Person);  // 输出为false ,但我们的本意是要这里为true的,表明p2是Person的实例。此时目的1达到了,目的2没达到。
</script>

但如果我们这么修正

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选