xinggevip

Es2015 传统方法创建类
index.html<!DOCTYPE html> <html lang="en&qu...
扫描右侧二维码阅读全文
15
2019/06

Es2015 传统方法创建类

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title>es6test</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but es6test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <script type="module">
      // 传统js创建类
      function Person(name,age){
        this.name = name;
        this.age = age;
      };
      Person.prototype.showName = function (){
        return "名字为:" + this.name;
      };
      Person.prototype.showAge = function (){
        return "年龄为:" + this.age;
      };
      let p1 = new Person('星哥',18);
      console.log(p1.showName()); // 名字为:星哥
      console.log(p1.showAge());  // 年龄为:18

      // Object.assign添加对象方法
      Object.assign(Person.prototype,{
        speak(){
          return this.name + "说话";
        },
        eat(){
          return this.name + "吃饭";
        }
      });
      console.log(p1.speak());  // 星哥说话
      console.log(p1.eat());    // 星哥吃饭

    </script>
    <!-- built files will be auto injected -->
  </body>
</html>
Last modification:June 24th, 2019 at 09:56 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment