JavaScript的__proto__、prototype和继承

前端开发 作者: 2024-08-22 13:15:01
JavaScript也是可以“继承”的! 各位看官或是好奇,或是一知半解。什么是prototype,__proto__,constructor、哪种继承方式好。今天就在这交流交流。 什么是protot

什么是prototype,__proto__,constructor


new关键词做了什么

1 //例如
2 var child = new Parent();
3 
4 上面这句代码就等于下面三句
5 var child = {};
6 child.__proto__ = Parent.prototype;
7 Parent.call(child);
var child2 = new child()

 哪种继承方式好

 1 function Cat(name){
 2   Animal.call(this);
 3   this.name = name || 'Tom';
 4 }
 5 ((){
 6    创建一个没有实例方法的类
 7   var Super = (){};
 8   Super.prototype = Animal.prototype;
 9   将实例作为子类的原型
10   Cat.prototype =  Super();
11 })();
12 
13  Test Code
14 var cat =  Cat();
15 console.log(cat.name);
16 console.log(cat.sleep());
17 console.log(cat instanceof Animal);  true
18 console.log(cat instanceof Cat); true
19 
20 感谢 @bluedrink 提醒,该实现没有修复constructor。
21 
22 Cat.prototype.constructor = Cat;  需要修复下构造函数
2   Animal.call(3   5 Cat.prototype = new Animal();

第5行代码相当于:
Cat.prototype = {}
Cat.prototype.__proto__ = Animal.prototype
Animal.call(Cat.prototype) //这一步是多余的并不需要

所以 var Super = function(){}; 一个空方法来代替,因为只需要

Cat.prototype.__proto__ = Animal.prototype 就可以了
而现在Super.prototype = Animal.prototype 因此这个方法是最完美的
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66683.html