Blogger Information
Blog 52
fans 1
comment 1
visits 38820
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示作用域与闭包; 2. 实例演示类与类的继承
小丑0o鱼
Original
405 people have browsed it

1. 作用域 1). 全局作用域,默认的,不可删除,如果在是浏览器中运行js,那么全局对象就是window
let site = “google”; console.log(site); console.log(window.site);

2). 函数作用域, 仅限在当前作用域内访问, 外部不可见,否则会报错。

作用域链, 自身查找,如果没有就返回上一级 function getSite() { let domain = google.com return `${site} [${domain}]; console.log(getSite()); 3). 块作用域,包在大括号里的语句就是块 {var a = 1; var B = 2;} console.log(a, B);

2. 闭包

  1. 能够访问自由变量的函数
  2. 在函数A内部有个函数B,函数B可以访问函数A中的变量,函数B就是闭包
  3. 通过闭包来访问内部的私有变量
  1. function sum(a, b) {
  2. return a + b + c;
  3. }
  4. console.log(sum(4, 5));
  5. function Hello() {
  6. let email = abc@abc.com”;
  7. return function d(){
  8. return email;
  9. },
  10. };
  11. console.log(Hello());

2. 类与类的继承

  1. constructor是类的构造函数 用与传递参数 返回实例对象,通过new生成实例时自动调用该方法.
  1. <script>
  2. function User(name, email) {
  3. this.name = name;
  4. this.email = email;
  5. this.show = function () {
  6. return { name: this.name, email: this.email };
  7. };
  8. }
  9. const user = new User(“Peter”, abc@abc.com”);
  10. console.log(user);
  11. </script>
  1. 原型共享方法,通过对象来调用
  1. <script>
  2. class User1 {
  3. constructor(name, email) {
  4. this.name = name;
  5. this.email = email;
  6. }
  7. show() {
  8. return { name: this.name, email: this.email };
  9. }
  10. }
  11. const user1 = new User1(“Bill”, ab@ab.com”);
  12. console.log(user1);
  13. console.log(user1.show());
  14. </script>

继承,是对父类进行一些扩展,添加一些新的属性或方法

  1. class Child extends User1 constructor(name, email, gender) {
  2. super(name, email);
  3. this.gender = gender;
  4. }
  5. show() {
  6. return { name: this.name, email: this.email, gender: this.gender };
  7. }
  8. }
  9. const child = new Child("Bob", "oy@qq.com", "male");
  10. console.log(child.show());
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post