通过函数传递“this”时,我是否可以无法访问“this”的属性

Can I not access attributes of 'this' when passing `this` through a function?

本文关键字:this 属性 是否 访问 函数      更新时间:2023-09-26

注意:整个问题基于问题是语法错误的场景;传递"this"实际上没有问题。这个问题应该结束了。

例如,以下工作:

$('.base-icons').click(function () {
   selectedIcon($(this).attr("src").split(/'/('/*)/));
});
var selectedIcon = function(myObj) {
   console.log(myObj);
};

并按预期打印缩短的字符串。以下方法不起作用

$('.base-icons').click(function () {
   selectedIcon(this);
});
var selectedIcon = function(myObj) {
   console.log($(myObj).attr("src").split(/'/('/*)/)[6]);
};

因为它打印undefined.为什么?谢谢。

例如,以下工作:

selectedIcon($(this).attr("src").split(/'/('/!*)/)[6])
var selectedIcon = function(myObj) {
   console.log(myObj)
}

并按预期打印缩短的字符串。以下方法不起作用:

selectedIcon(this)
var selectedIcon = function(myObj) {
   console.log($(myObj).attr("src").split(/'/('/!*)/)[6])
}

因为它打印未定义。为什么?谢谢。

javascript提问时selectedIcon undefined,导致TypeError

问题中的两个示例都应返回错误。

Uncaught TypeError: selectedIcon is not a function

window.onerror = function(e) {
  console.info(e);
  alert(e);
}
selectedIcon("abc");
var selectedIcon = function (myObj) {
   alert(myObj)
}

是的,您可以在通过函数传递this时访问this的属性。

您可以像这样访问此属性。

$(this).attr("href");