JavaScript学习笔记4:面向对象

本文介绍JavaScript中面向对象的实现方式,包括构造函数、原型继承、ES6类继承等概念,并探讨了如何使用Promise进行异步任务管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

面向对象

创建对象

// 构造函数
function Student1(name) {
    this.name = name;
    this.hello = function () {
        console.log('Hello, ' + this.name + '!');
    }
}
// 使用关键字new就变为构造函数
var xiaoming = new Student1('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!

// 让创建的对象共享一个hello函数
function Student2(name) {
    this.name = name;
}
// 把函数移到对象原型上
Student2.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

var xiaohong = new Student2('小红');
var xiaowang = new Student2('小王');
xiaohong.hello === xiaowang.hello; // true

// 封装构造函数
function Student3(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
}

Student3.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

function createStudent3(props) {
    return new Student3(props || {})
}
// 封装构造函数优点
// 一是不需要new来调用
// 二是参数非常灵活,可以不传,也可以这么传
var xiaojun = createStudent3({
    name: '小军'
});
xiaojun.grade; // 1

原型继承

function Student(props) {
    this.name = props.name || 'Unnamed';
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
}

// 原型继承实现方式
// 定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this;
// 借助中间函数F实现原型链继承,最好通过封装的inherits函数完成;
// 继续在新的构造函数的原型上定义新方法。

// PrimaryStudent构造函数:
function PrimaryStudent(props) {
    Student.call(this, props);
    this.grade = props.grade || 1;
}

function inherits(Child, Parent) {
    // 空函数F:
    var F = function () {};
    // 把F的原型指向Student.prototype
    F.prototype = Parent.prototype;
    // 把PrimaryStudent的原型指向一个新的F对象
    // F对象的原型正好指向Student.prototype
    Child.prototype = new F();
    // 把PrimaryStudent原型的构造函数修复为PrimaryStudent
    Child.prototype.constructor = Child;
}

// 实现原型继承链:
inherits(PrimaryStudent, Student);

// 继续在PrimaryStudent原型(就是new F()对象)上定义方法
PrimaryStudent.prototype.getGrade = function () {
    return this.grade;
};

// 创建xiaoming:
var xiaoming = new PrimaryStudent({
    name: '小明',
    grade: 2
});
xiaoming.name; // '小明'
xiaoming.grade; // 2

// 验证原型:
xiaoming.__proto__ === PrimaryStudent.prototype; // true
xiaoming.__proto__.__proto__ === Student.prototype; // true

// 验证继承关系:
xiaoming instanceof PrimaryStudent; // true
xiaoming instanceof Student; // true

class继承

// ES6引入新的关键字class,让定义类更简单
class Student {
    constructor(name) {
        this.name = name;
    }

    // 没有function关键字
    hello() {
        console.log('Hello, ' + this.name + '!');
    }
}

var xiaoming = new Student('小明');
xiaoming.hello();

// 定义PrimaryStudent继承与Student
class PrimaryStudent extends Student {
    constructor(name, grade) {
        super(name); // 记得用super调用父类的构造方法!
        this.grade = grade;
    }

    // 没有function关键字
    myGrade() {
        console.log('I am at grade ' + this.grade);
    }
}

var xiaohong = new PrimaryStudent('小红', 2);
xiaohong.hello();
xiaohong.myGrade();

promise

// ES6统一规范了Promise,可以链式执行异步任务
function test(resolve, reject) {
    var timeout = Math.random() * 2;
    console.log('set timeout to: ' + timeout + ' seconds.');
    setTimeout(function () {
        if (timeout < 1) {
            console.log('timeout < 1 call resolve()...');
            resolve('200 OK');
        } else {
            console.log('timeout >= 1 call reject()...');
            reject('timeout in ' + timeout + ' seconds.');
        }
    }, timeout * 1000);
}

new Promise(test).then(function (result) {
    console.log('成功:' + result);
}).catch(function (reason) {
    console.log('失败:' + reason);
});

// 串行执行一系列需要异步计算获得结果的任务
// 0.5秒后返回input*input的计算结果:
function multiply(input) {
    return new Promise(function (resolve, reject) {
        console.log('calculating ' + input + ' x ' + input + '...');
        setTimeout(resolve, 500, input * input);
    });
}

// 0.5秒后返回input+input的计算结果:
function add(input) {
    return new Promise(function (resolve, reject) {
        console.log('calculating ' + input + ' + ' + input + '...');
        setTimeout(resolve, 500, input + input);
    });
}

var p = new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log('start serial Promise...');
        resolve(123);
    }, 2500);
});
p.then(multiply)
    .then(add)
    .then(multiply)
    .then(add)
    .then(function (result) {
        console.log('Got value: ' + result);
    });

// Promise.all 并行执行异步任务,等待都完成后执行then
var p1 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log('Start parallel Promise: P1');
        resolve('P1');
    }, 5500);
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        console.log('Start parallel Promise: P2');
        resolve('P2');
    }, 5600);
});
// 同时执行p1和p2,并在它们都完成后执行then:
Promise.all([p1, p2]).then(function (results) {
    console.log('Get P1 P2 result: ' + results); // 获得一个Array: ['P1', 'P2']
});

// Promise.race() 并行执行异步任务,只获取先返回的结果
var p1 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 6500, 'P1');
});
var p2 = new Promise(function (resolve, reject) {
    setTimeout(resolve, 6600, 'P2');
});
Promise.race([p1, p2]).then(function (result) {
    console.log(result); // 'P1'
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值