JavaScript面向对象编程

面向对象编程

由于js没有类与实例的概念,创建对象一般可以用

var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};

var xiaoming = {
    name: '小明'
};

xiaoming.__proto__ = Student;
xiaoming.run()

__proto__相当于使xiaoming继承Student,并集成了Student中的默认值。

构造函数
function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
    this.hello = function(){
        console.log('hello');
    }
}

var xiaoming = new Student({
    name: '小明'
});

若使用new,则函数被视为构造函数,参数一般传入一个props对象或多个普通参数,||的作用的默认值。

class

在最新的标准可以通过class来构造对象了

class PrimaryStudent extends Student {
    //构造函数
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }
	//注意不用加function
    myGrade() {
        alert('I am at grade ' + this.grade);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值