function Zombie(name,hurt,health,speed){ this.name = name; this.hurt = hurt; this.health = health; this.speed = speed; this.attack = function(){ console.log(this.name + " attack"); } } var zombie=new Zombie("僵尸",10,100,10); var flag_zombie=new Zombie("旗帜僵尸",10,100,15); zombie.attack(); flag_zombie.attack();
new的作用
0.调用方法
1.在调用时,执行方法体之前,声明一个空对象var obj={}
2.让方法体内的this强行指向这个空对象,从而在执行方法体时把属性声明到创建的空对象内,填充对象
即obj.name=name....
3.
4.把创建好的对象返回 return obj
最终把执行的方法赋值给变量,就相当于var a=obj
a就是我们实例化出的对象
为什么zombie.attack();和flag_zombie.attack();是两个方法
因为在实例化zombie和flag_zombie是方法内创建了两个对象
虽然都是attack方法,但是放入了两个对象内,所以是两个方法
如何解决?
JS中没有“类”这个东西,它只是一个在实现面向对象的过程中辅助我们理解的一个概念
面向对象的起点是:
function Zombie(name,hurt,health,speed){...}
这个Zombie方法被称为构造函数,有了构造函数,就会自动生成一个对象来包裹这个构造函数,这个对象被称为原型对象
原型
第一步:人为声明构造函数Zombie
第二步:自动生成原型对象,只要由构造函数,就一定存在原型
虚拟概念类:类中包括原型(构造方法在原型中)
//声明一个Zombie类
//从构造函数开始
function Zombie(name,hurt,health,speed){
this.name = name;
this.hurt = hurt;
this.health = health;
this.speed = speed;
this.attack = function(){
console.log(this.name + " attack");
}
}
//有了构造函数,类就形成了
//同时形成的还有类的原型对象
//如何使用?
//通过类调用原型对象prototype
console.log(Zombie.prototype);
//作用把方法注册到原型对象中,由实例化而来的对象可以直接调用原型中的方法
var zombie=new Zombie("僵尸",10,100,10);
var flag_zombie=new Zombie("旗帜僵尸",10,100,15);
zombie.attack();//正常调用
flag_zombie.attack();//正常调用
console.log(zombie.attack==flag_zombie.attack)//true
//实例化出来的zombie和flag_zombie调用的attack方法,都是原型上的方法
通过对象,调用原型__proto__
console.log(zombie.__proto__);
console.log(flag_zombie.__proto__==Zombie.prototype);//true
由类实例化而来的对象的原型方法和类的原型对象是同一个对象
综上:不管new出多少个对象,所有对象的原型对象都指向类的原型对象
所以zombie和flag_zombie方法是同一个方法
图文解释:
JS底层规定,当存在 zombie.prototype.attack()时就一定存在zombie.attack()
我们使用的是对象
但是有时要根据不同的类的对象执行不同的方法
如何判断对象的类?
//植物类
function Plant(name, game, hurt, cost, burial, introduce){
this.name = name;
this.game = game;
this.hurt = hurt;
this.cost = cost;
this.burial = burial;
this.introduce = introduce;
}
//僵尸类
function Zombie(name,hurt,health,speed){
this.name = name;
this.hurt = hurt;
this.health = health;
this.speed = speed;
this.attack = function(){
console.log(this.name + " attack");
}
}
//实例化对象
var plant = new Plant("sunflower",1,1,1,1,"introduce");
var zombie = new Zombie("zombie",1,1,1);
//类的原型
console.log(Plant.prototype)
//构造函数
console.log(Plant.prototype.constructor)
//实例化对象的原型
console.log(plant.__proto__)
//通过实例化对象的构造函数
console.log(plant.__proto__.constructor)
//通过实例化对象直接访问构造函数
console.log(plant.constructor)
//判断plant是不是Zombie类
console.log(plant.constructor == Zombie)//false
//判断plant是不是Plant类
console.log(plant.constructor == Plant)//true