定义
创建类,其实就是方法
function Person(name,age){
定义属性
this.name=name;
this.age=age;
定义方法
this.func=function(){
alert(this.name)
}
}
创建实例化对象
var one = new Person('张三',10)
var two = new Person('李四',10)
one.func() //张三
two.func() //李四
instanceof 检查一个对象是否属于摸个类
console.log(one instanceof Person) >>>true
原型对象:
目的:节省创建实例对象时,开辟多的资源,是一种优化方法
使用:将固有的,不可能变化的属性与方法定义在全局
function Person(name,age){
this.name=name;
this.age=age;
this.func=function(){
alert(this.name)
}
}
Person.prototype.func=function(){
alert(this.name)
}
创建实例化对象
var one = new Person('张三',10)
var two = new Person('李四',10)
one.func() //张三
two.func() //李四
class Person{
constructor(name,age){
this.name=name;
this.age=age;
}
func(){
alert(this.name)
}
static static_fun(){
alert('我是静态方法,只能通过类调用')
}
}
var one = new Person('张三',10)
var two = new Person('李四',10)
one.func() //张三
two.func() //李四
Person.static_fun()
this
1.以方法调用时,this指的是调用方法的那个对象
2.以函数调用时,this永远指window
3.以实例调用时,this指的是改实例
方法重写
Person.prototype.toString=function(){
代码块
return ...
}
继承
function Animal(name){
this.name=name
}
Animal.prototype.eat=function(food){
alert(this.name+food)
}
function Cat(){
this.name='cat'
}
Cat.prototype = new Animal();
var cat = new Cat()
cat.eat('吃鱼')
class Person{
constructor(name,age){
this.name=name;
}
func(food){
alert(this.name+food)
}
}
class Man extends Person{
constructor(name){
super(name)
}
}
var man = new Man('张三')
man.func('吃饭')
多态
class Animal{
eat(){
alert('啥都吃')
}
}
class Cat extends Animal{
eat(){
alert('猫吃鱼')
}
}
class Dog extends Animal{
eat(){
alert('狗吃骨头')
}
}
class Person{
feed(Animal){
Animal.eat()
}
}
var cat = new Cat();
var dog = new Dog();
var p = new Person()
p.feed(cat)
p.feed(dog)
垃圾回收
js有自己的垃圾回收机制,我们只需将对象=null后会自动回收
例如:one=null;