030 -- 自找麻烦之 js设计模式

1. 合格工程师:前端有一定的设计能力(面试必考,项目负责人必要基础)

2. 面向对象三要素:继承,封装,多态

3. 先学点面向对象之搭建开发环境:(搭建完本地开发就能实时刷新浏览器)

  • 项目根目录新建文件 webpack.dev.config.js(内容如4)
  • 项目根目录新建 package.json 文件(内容如4),npm i 即可
  • 项目根目录新建 .babelrc 文件(内容如4)
  • npm run dev

4. webpack.dev.config.js 文件


const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: './src/index.js',  //入口文件,自己新建好
    output: {
        path: __dirname,
        filename: './release/bundle.js'  // release 会自动创建
    },
    plugins: [  // 插件列表
        new HtmlWebpackPlugin({
            template: './index.html'  // bundle.js 会自动注入
        })
    ],
    devServer: {
        contentBase: path.join(__dirname, "./release"),  // 根目录
        open: true,  // 自动打开浏览器
        port: 9000,   // 端口
        proxy: {
            '/api/*': {
                target: 'http://localhost:8880'
            }
        }
    },
    module: {
        rules: [{
            test: /\.js?$/,
            exclude: /(node_modules)/,
            loader: 'babel-loader'
        }]
    }
}

package.json文件

{
  "name": "es6",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "webpack-dev-server --config ./webpack.dev.config.js --mode development"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-polyfill": "^6.26.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-latest": "^6.24.1",
    "html-webpack-plugin": "^3.2.0",
    "webpack": "^4.8.3",
    "webpack-cli": "^2.1.3",
    "webpack-dev-server": "^3.1.4"
  },
  "dependencies": {
    "javascript-state-machine": "^3.0.1",
    "jquery": "^3.3.1"
  }
}

.babelrc文件

{
    "presets": ["es2015", "latest"],
    "plugins": ["transform-decorators-legacy"]
}

5. 封装指某个对象里面的属性和方法把它保密起来,不让别人看见(ES6暂时还不支持,ts可以)

  • public 完全开放
  • protected 对子类开放
  • private 对自己开放

6. 多态指同一接口不同实现(前端用的比较少,因为前端没有接口的概念)

7. 继承写法

class People {
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    eat() {
        alert(`${this.name} eat something`)
    }
    speak() {
        alert(`My name is ${this.name}, age ${this.age}`)
    }
}

class Student extends People {
    constructor(name, age, number) {   
        super(name, age)    // 把name和age传递给父类的构造函数来执行
        this.number = number  // 我们自己处理number
    }
    study() {
        alert(`${this.name} study`)
    }
}

let xiaoming = new Student('xiaoming', 10, 'A1')
xiaoming.study()
console.log(xiaoming.number)
let xiaohong = new Student('xiaohong', 11, 'A2')
xiaohong.study()

 

你可能感兴趣的:(JavaScript,设计模式)