js中的面向对象

主要内容:

  • 1.ES5中面向对象
  • 2.ES6中面向对象
  • 3.promise

1.ES5中面向对象

function Point(x, y){
    this.x = x;
    this.y = y;
}

// 给父级绑定方法
Point.prototype.toSting = function(){
    return '(' + this.x + ',' + this.y + ')';
}

var p = new Point(10, 20);
console.log(p.x)
p.toSting();

// 继承
function ColorPoint(x, y, color){
    Point.call(this, x, y);
    this.color = color;
}
// 继承父类的方法
ColorPoint.prototype = Object.create(Point.prototype);
// 修复 constructor
ColorPoint.prototype.constructor = Point;
// 扩展方法
ColorPoint.prototype.showColor = function(){
    console.log('My color is ' + this.color);
}

var cp = new ColorPoint(10, 20, "red");
console.log(cp.x);
console.log(cp.toSting());
cp.showColor()

2.ES6中面向对象

class Point{
    constructor(x, y){
        this.x = x;
        this.y = y;
    }  // 不要加逗号
    toSting(){
        return `(${this.x}, ${this.y})`;
    }
}

var p = new Point(10, 20);
console.log(p.x)
p.toSting();

class ColorPoint extends Point{
    constructor(x, y, color){
        super(x, y);  // 调用父类的constructor(x, y)
        this.color = color;
    }  // 不要加逗号
    showColor(){
        console.log('My color is ' + this.color);
    }
}

var cp = new ColorPoint(10, 20, "red");
console.log(cp.x);
cp.toSting();
cp.showColor()

3.promise

  • Promise 是异步编程的一种解决方案,比传统的解决方案(回调函数和事件)更合理、更强大。它由社区最早提出和实现,ES6 将其写进了语言标准,统一了用法,原生提供了Promise对象。
  • 使用Promise的优势是有了Promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise对象提供统一的接口,使得控制异步操作更加容易。

用法示例:

const promiseObj = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

Promise构造函数接受一个函数作为参数,该函数的两个参数分别是resolvereject。它们是两个函数,由 JavaScript 引擎提供,不用自己部署。

Promise实例生成以后,可以用then方法分别指定resolved状态和rejected状态的回调函数。

promiseObj.then(function(value) {
  // success
}, function(error) {
  // failure
});

then方法可以接受两个回调函数作为参数。第一个回调函数是Promise对象的状态变为resolved时调用,第二个回调函数是Promise对象的状态变为rejected时调用。其中,第二个函数是可选的,不一定要提供。这两个函数都接受Promise对象传出的值作为参数。

我们还可以将上面的代码写成下面这种方式:

promiseObj
.then(function(value) {
  // success
})
.catch(function(error) {
  // failure
});

其实Promise.prototype.catch方法是.then(null, rejection)的别名,用于指定发生错误时的回调函数

注:

本文中的些许示例来自阮一峰的《ECMAScript 6 标准入门》

附:

想了解更多有关ES6标准内容,推荐阅读:http://es6.ruanyifeng.com/

posted @ 2019-01-08 21:38  一路向北_听风  阅读(168)  评论(0)    收藏  举报