js基础巩固(一)

js基本数据类型:

1.Number( Int, Float, NaN, Infinity)

2.String (单引号、双引号包裹的)

3.Boolean(true, false)

4.Object(无序名值对)【引用类型】

5.Null(值为null,表示为空)

6.Undefined(值为undefined,表示a.已声明但未赋值;b.获取对象属性不存在)

 

typeof  VS  instanceof

获取数据类型函数: typeof(a) (除了booleam、Number、String、function、undefined等,其余均返回Object)

判断a是否为b的实例: instanceof(可以具体到是Array、Null等)

例如: a instanceof Array ?  true  : false;

 

call VS apply VS bind

obj.call(thisObj, a, b) // thisOb继承了Array的属性跟方法(a,b为假设的参数)

obj.apply(thisObj, [a, b]) // apply效果与上相同,只是传参为数组形式

add(5,3); //8

add.call(sub, 5, 3); //8

add.apply(sub, [5, 3]); //8

sub(5, 3); //2 sub.call(add, 5, 3); //2

sub.apply(add, [5, 3]); //2

obj.bind(thisObj, a, b) // thisObj同样继承了Array的属性跟方法,不同之处在于,bind方法不会立即执行

add.bind(sub, 5, 3); //不返回8

add.bind(sub, 5, 3)(); //8

 

new Function创建函数跟关键字function创建函数的区别

所有的函数都是Function对象,通过new Function创建的函数,即由 Function 构造函数创建的函数不会创建当前环境的闭包,它们总是被创建于全局环境,因此在运行时它们只能访问全局变量和自己的局部变量,不能访问它们被 Function 构造函数创建时所在的作用域的变量。

var x = 10;

function createFunction1() {
    var x = 20;
    return new Function('return x;'); // 这里的 x 指向最上面全局作用域内的 x
}

function createFunction2() {
    var x = 20;
    function f() {
        return x; // 这里的 x 指向上方本地作用域内的 x
    }
    return f;
}

var f1 = createFunction1();
console.log(f1());          // 10
var f2 = createFunction2();
console.log(f2());  // 20

虽然这段代码可以在浏览器中正常运行,但在 Node.js 中 f1() 会产生一个“找不到变量 x”的 ReferenceError。这是因为在 Node 中顶级作用域不是全局作用域,而 x 其实是在当前模块的作用域之中。

 

 类
static静态方法,不能通过实力化对象调用,通常是类的一个工具函数。
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    static displayName = "Point";

    static distance(a, b) {
        const dx = a.x - b.x;
        const dy = a.y - b.y;
        return Math.hypot(dx, dy);
    }
}

const p1 = new Point(5, 5);
const p2 = new Point(10,10);
p1.displayName;
// undefined
p1.distance;
// undefined

console.log(Point.displayName);
// "Point"
console.log(Point.distance(p1, p2));
// 7.0710678118654755

类内部的代码总是在严格模式下执行,所以当调用原型或静态方法时,this为undifined.

class Animal {
  speak() {
    return this;
  }
  static eat() {
    return this;
  }
}

let obj = new Animal();
obj.speak(); // Animal {}
let speak = obj.speak;
speak(); // undefined

Animal.eat() // class Animal
let eat = Animal.eat;
eat(); // undefined

 

posted @ 2023-05-04 10:34  南韵  阅读(12)  评论(0编辑  收藏  举报