首页 > 语言 > JavaScript > 正文

Javascript中的prototype与继承

2024-05-06 15:01:42
字体:
来源:转载
供稿:网友

通常来说,javascript中的对象就是一个指向prototype的指针和一个自身的属性列表。javascript创建对象时采用了写时复制的理念。

只有构造器才具有prototype属性,原型链继承就是创建一个新的指针,指向构造器的prototype属性。

prototype属性之所以特别,是因为javascript时读取属性时的遍历机制决定的。本质上它就是一个普通的指针。

构造器包括:

1.Object
2.Function
3.Array
4.Date
5.String

下面我们来举一些例子吧

//每个function都有一个默认的属性prototype,而这个prototype的constructor默认指向这个函数//注意Person.constructor 不等于 Person.prototype.constructor. Function实例自带constructor属性functionPerson(name){this.name = name;};Person.prototype.getName =function(){returnthis.name;};var p =newPerson("ZhangSan");console.log(Person.prototype.constructor===Person);// trueconsole.log(p.constructor===Person);// true ,这是因为p本身不包含constructor属性,所以这里其实调用的是Person.prototype.constructor

我们的目的是要表示

1. 表明Person继承自Animal

2. 表明p2是Person的实例

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

functionPerson(name){this.name = name;};Person.prototype.getName =function(){returnthis.name;};var p1 =newPerson("ZhangSan");console.log(p.constructor===Person);// trueconsole.log(Person.prototype.constructor===Person);// truefunctionAnimal(){}Person.prototype =newAnimal();//之所以不采用Person.prototype = Animal.prototype,是因为new 还有其他功能,最后总结。var p2 =newPerson("ZhangSan");//(p2 -> Person.prototype -> Animal.prototype, 所以p2.constructor其实就是Animal.prototype.constructor)console.log(p2.constructor===Person);// 输出为false ,但我们的本意是要这里为true的,表明p2是Person的实例。此时目的1达到了,目的2没达到。

但如果我们这么修正

Person.prototype = new Animal();Person.prototype.constructor = Person;

这时p2.consturctor是对了,指向的是Person,表示p2是Person类的实例,但是新问题出现了。此时目的2达到了,目的1没达到。

目的1和目的2此时互相矛盾,是因为此时prototype表达了矛盾的两个意思,

1. 表示父类是谁

2. 作为自己实例的原型来复制

因此我们不能直接使用prototype属性来表示父类是谁,而是用getPrototypeOf()方法来知道父类是谁。 

Person.prototype =newAnimal();Person.prototype.constructor=Person;var p2 =newPerson("ZhangSan");p2.constructor//显示 function Person() {}Object.getPrototypeOf(Person.prototype).constructor//显示 function Animal() {}            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选