当前位置 : 主页 > 手机开发 > harmonyos >

JS原型链学习笔记

来源:互联网 收集:自由互联 发布时间:2023-08-25
Animal-Dog-jiwawa例子 “Animal拥有name属性和laugh方法 Dog继承Animal jiwawa(吉娃娃)是Dog的实例” 各种失败的尝试: 1,错误,dog只是Animal的实例,不是继承自它的后嗣 1 function Animal (name){2 this.n


Animal-Dog-jiwawa 例子

“Animal拥有name属性和laugh方法
Dog 继承 Animal 
jiwawa(吉娃娃)是Dog 的实例”

各种失败的尝试:

1,错误,dog只是Animal的实例,不是继承自它的后嗣



1 function Animal (name){
2     this.name=name;
3     this.laugh=function(){return "Haha"};
4 }
5 var dog = new Animal("dog") ;
6 console.log(dog.name);
7 dog.laugh();



2, 错误,把Dog的prototype给了Animal



1 function  Animal(name){
2    this.name=name;
3    this.laugh = function(){return "Haha"};}
4 var Dog=new Object();
5 var Dog = Object.create(Animal);   
6 //把Dog的prototype给了Animal
7 
8 var jiwawa = new Dog("ss");
9 jiwawa.laugh()



3,写法错误 Dog.prototype= new Animal(); 



function  Animal(name){
   this.name=name;
   this.laugh = function(){return "Haha"};}
var Dog=new Object();
Dog.prototype= Animal;   
//写法错误 Dog.prototype= new Animal(); 

var jiwawa = new Dog("ss");
jiwawa.laugh()



4,自有属性不要放进原型中



function  Animal(){}
   Animal.prototype.name="sth";   //自有属性不要放进原型中
   Animal.prototype.laugh = function(){return "Haha"};

function Dog (){};
Dog.prototype= Animal.prototype
var jiwawa = new Dog();
jiwawa.laugh();



最后代码: 



function Animal(name){
    this.name=name;
}
Animal.prototype = {
    laugh : function(){return "haha"}  
}
function Dog(name){
    Animal.call(this,name);  
}
Dog.prototype=new Animal(); 
var Jiwawa = new Dog("jiji");
Jiwawa.laugh();



 

网友评论