IP地址检测
视频播放器
输入关键词搜索
登录
javascript高级教程

javascript高级教程

2023-03-08
暂无分类

this作用域

在javascript中,this的指向不是固定的,而是指向调用者对象

1.全局的函数调用

function globalTest() {
    this.name = "global this";
    console.log(this.name);
}
globalTest(); //输出 global this

this代表全局对象window

2.对象方法的调用

function showName() {
    console.log(this.name);
}
var obj = {};
obj.name = "ooo";
obj.show = showName;
obj.show(); //输出 ooo

调用者是obj,因此this指向obj

3.构造函数的调用

function showName() {
    this.name = "showName function";
}
var obj = new showName();
console.log(obj.name); //showName function

调用者是函数实例本身,因此this指向函数实例

4.apply/call调用时的this

apply和call都是为了改变函数体内部的this指向

  • call方法

    function.call(thisArg, arg1, arg2, ...)
    

    并将函数中的this关键字绑定到thisArg上,如果没有提供thisArg参数,那么Global对象被用作thisArg。

  • apply方法

    function.apply(thisArg, [argsArray])
    

call() 和 apply() 方法的区别在于传递参数的方式不同。call() 方法会将参数逐个传递给函数,而 apply() 方法需要将参数封装成一个数组传递给函数

bind 函数绑定

在 JavaScript 中,bind() 方法可以用于创建一个新函数,并将函数中的 this 关键字绑定到指定的对象上

bind()方法的语法如下

function.bind(thisArg[, arg1[, arg2[, ...]]])

示例代码:

const obj = {
  name: 'John',
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};

const boundGreet = obj.greet.bind(obj);
boundGreet(); // 输出:Hello, John!

bind到自己,意味着this指针没有改变,这里可以理解成复制函数

判断数组是否为空

const arr = []
if(Array.isArray(arr) && arr.length>0){
    console.log("is array")
} else {
    console.log("not array")
}

判断字符串是否为空

如果一个变量的值为null、undefined、空字符串或者0或NaN,都被当作false。可以利用这个特性,来判断空字符串

const str = ''
if (str) {
    //字符串中有内容
} else {
    //str的值为undefined/null/''/NaN/0
}

// 或者
console.log(str ? '字符串不为空' : '字符串为空')
console.log(str || "123") // str为空时打印123

Proxy代理对象

Proxy 类是 JavaScript 中的一个内置类,用于创建代理对象,可以拦截和自定义目标对象的操作

// 目标对象
const target = {
  name: 'John',
  age: 30,
};

// 处理程序对象
const handler = {
  get: function(target, prop) {
    console.log(`获取属性 ${prop}`);
    return target[prop];
  },

  set: function(target, prop, value) {
    console.log(`设置属性 ${prop} 值为 ${value}`);
    target[prop] = value;
  },

  // 其他陷阱函数...
};

// 创建代理对象
const proxy = new Proxy(target, handler);

// 通过代理对象访问属性
console.log(proxy.name); // 获取属性 name

// 通过代理对象设置属性
proxy.age = 35; // 设置属性 age 值为 35

当通过代理对象访问属性时,get 陷阱函数会被触发,并显示相应的日志信息。当我们通过代理对象设置属性时,set 陷阱函数会被触发,并显示相应的日志信息。

Proxy 类还提供了其他一些陷阱函数,例如 apply 用于拦截函数调用、has 用于判断属性是否存在等。你可以根据需要在处理程序对象中添加适合的陷阱函数来实现自定义的操作逻辑。

const target = function (message) {
  console.log('目标函数被调用,参数为:', message);
};

const handler = {
  apply: function(target, thisArg, argumentsList) {
    console.log('拦截到函数调用');
    console.log('目标函数:', target);
    console.log('this 上下文:', thisArg);
    console.log('参数列表:', argumentsList);

    // 执行目标函数
    return target.apply(thisArg, argumentsList);
  }
};

const proxy = new Proxy(target, handler);

// 调用代理对象,会触发 apply 陷阱函数
proxy('Hello, Proxy!');
THE END
0/500
暂无评论
📢网站公告
欢迎来到这里
⚙️实用工具
html转pdfmarkdown编辑器
本站推荐:腾讯云服务器仅需2.3折 (点击直达)
用户协议
隐私政策
Build Time: 2025-04-26 11:07:00