深入了解javascript中的prototype与继承 |
本文标签:js,prototype,继承 通常来说,javascript中的对象就是一个指向prototype的指针和一个自身的属性列表 。javascript创建对象时采用了写时复制的理念 。 下面我们来举一些例子吧 复制代码 代码如下: <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> 我们的目的是要表示 我们修改一下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.constructor = Person; var p2 = new Person("ZhangSan"); p2.constructor //显示 function Person() {} Object.getPrototypeOf(Person.prototype).constructor //显示 function Animal() {} 就把这两个概念给分开了
创建一个空白对象 创建一个指向Person.prototype的指针 将这个对象通过this关键字传递到构造函数中并执行构造函数 。 如果采用Person.prototype = Animal.prototype来表示Person继承自Animal, instanceof方法也同样会显示p也是Animal的实例,返回为true.之所以不采用此方法,是因为下面两个原因: 1.new 创建了一个新对象,这样就避免了设置Person.prototype.constructor = Person 的时候也会导致Animal.prototype.constructor的值变为Person,而是动态给这个新创建的对象一个constructor实例属性,这样实例上的属性constructor就覆盖了Animal.prototype.constructor,这样Person.prototype.constructor和Animal.prototype.contructor就分开了 。 2.Animal自身的this对象的属性没办法传递给Person 通过使用 hasOwnProperty()方法,什么时候访问的是实例属性,什么时候访问的是原型属性就 一清二楚了 。 |