js_类

定义

创建类,其实就是方法
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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值