mobx学习笔记02——mobx基础语法(class)

新的语法可能不被浏览器支持,可以使用babel转换为浏览器支持的代码格式; 

为什么要定义class?

js是一门面向对象的编程语言。需要利用类来复用代码,提高编程效率。

需要什么样的class能力?

继承+多态

例子:在页面中显示Hello World!

1)创建工程文件夹,在该文件夹中创建src文件夹,在src文件夹中创建index.js文件,并在其中写入显示Hello World!的代码。

2)执行npm init -y 命令来创建包含默认内容的package.json文件

3)创建webpack配置文件 webpack.config.js。

    目前只需要配置能将新代码转换为老旧代码的功能:

const path = require('path');  //note的path模块用来处理路径信息
    const config = {
    mode:'development',
    entry:path.resolve(__dirname,'src/index.js'),
    output:{
    path:path.resolve(__dirname,'dist'),
    filename:'main.js'
    },
    module:{
     rules:[{
      test:/.js$/,
      exclude:/node_modules/,
      use:{
       loader:'babel-loader',
       options:{
       presets:['env'],
       }
      }
     }]
    },
    devtool:'inline-source-map'
    };
module.exports = config; 

 为了更方便的调用webpack,添加npm的script属性:

"start":"webpack -w”

监视文件更改,自动完成编译

 要安装以下依赖:

webpack、webpack-cli、babel-core、babel-preset-env、babel-loader

4)执行npm start,编译成功后,项目工程目录下会生成一个dist文件夹,文件夹中是

转换好的代码文件main.js

    报错:Error: Cannot find module '@babel/core'

  babel-loader@8 requires Babel 7.x (the package '@babel/core'). If you'd like to 

use Babel 6.x ('babel-core'), you should install 'babel-loader@7'.

    解决:安装@babel/core依赖:npm install --save-dev @babel/core

5) 创建html文件,在其中引用main.js文件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <meta name="viewport" content="width=device-width,
                   initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,
                   user-scalable=no"
         >
        <style type="text/css"></style>
    </head>
    <body>
    </body>
    <script src="dist/main.js"></script>
</html>                  

6)在浏览器中打开,页面中出现Hello World!,表示项目环境已经创建完成。

7)实现继承与多态。执行npm start,才能实时生成新的main.js,实时修改页面

function Animal(){}
   function Dog(){}
   //dog instanceof Animal => true
   //dog.__proto__.__proto__... === Animal.prototype
   Dog.prototype = Object.create(Animal.prototype);
   document.write(new Dog() instanceof Animal);// true 实现了继承 
//============================================
function Animal(){}
   function Dog(){}
   Object.defineProperties(Animal.prototype,{
    name:{
    value(){
     return 'Animal';
    }
   },
   say:{
    value(){
     return `I'm ${this.name()}`;
     }
    }
   })
   Dog.prototype = Object.create(Animal.prototype);
   document.write(new Dog().say());  //I'm Animal 实现了继承 
//=============================================
function Animal(){}
  function Dog(){}
  Object.defineProperties(Animal.prototype,{
    name:{
     value(){
      return 'Animal';
     }
    },
    say:{
     value(){
      return `I'm ${this.name()}`;
     }
    }
   })
   Dog.prototype = Object.create(Animal.prototype,{
    name:{
     value(){
      return 'Dog';
     }
    }
   });
   document.write(new Dog().say()); //I'm Dog  实现了多态 
//===========================================
   function Animal(){}
   function Dog(){}
   Object.defineProperties(Animal.prototype,{
    name:{
     value(){
      return 'Animal';
    }
   },
    say:{
     value(){
      return `I'm ${this.name()}`;
     }
    }
   })
   Dog.prototype = Object.create(Animal.prototype,{
    constructor:{
     value:Dog,
     enumerable:false
    },
    name:{
     value(){
      return 'Dog';
     }
    }
   });
   document.write(new Dog().say());
   console.log(Dog.prototype.constructor); //ƒ Dog() {}实现了完整的继承,很麻烦
//=========================================
   ES2015开始,JS支持了class语法
   class Animal{
    name(){
     return 'Animal';
    }
    say(){
     return `I'm ${this.name()}`;
    }
   }
   class Dog extends Animal{
    food = 'bone';//定义成员属性
    name(){
     return 'Dog';
    }
   }
   console.log(new Dog() instanceof Animal);//true 实现了继承

两次报错:

1⃣️Module build failed (from ./node_modules/babel-loader/lib/index.js):

  TypeError: /Users/mac/Desktop/testcode_jyt/mobx-test/src/index.js: Cannot read property 'bindings' of null

  解决:修改webpack配置文件为

 module: {
       rules:[{
        test: /.js$/,
        loader: 'babel-loader',
        exclude: __dirname + 'node_modules',
        include: __dirname + 'src',
           options: {
            presets: ['env']
        }
       }]
},

2⃣️ERROR in ./src/index.js 10:6

  Module parse failed: Unexpected token (10:6)

      You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders

                    | }

                    | class Dog extends Animal{

                    > food = 'bone';//定义成员属性

                    | name(){

                    | return 'Dog';

  解决:缺少babel插件,不能识别这一语法,安装即可。

      npm i babel-plugin-transform-class-properties -D

安装后在webpack配置文件中修改配置。

在options中增加plugins: ['transform-class-properties']

 

事实上我的还是报错,相同的错误。。试了很多办法也没解决。。。

 

解决方法:主要还是插件的版本和配置文件编写的问题,要对应上不同版本的写法。

https://www.cnblogs.com/superjishere/p/12096419.html

原文地址:https://www.cnblogs.com/superjishere/p/12067596.html