gpt4 book ai didi

JavaScript 库将其设置为一个元素

转载 作者:行者123 更新时间:2023-11-30 05:43:38 25 4
gpt4 key购买 nike

我正在开发一个类似 javascript 库的 jQuery。语法如下:

tex(selector).function();

在我的 javascript 库中,我有这个:

(function(){
var tex = function(selector){
//selection code here
},
tex.prototype = {
// prototype functions here
}
})();

我遇到的问题是如何将 this 设置为等于元素。我已经尝试过 this = document.getElement... 但它没有用。我知道 jQuery 以某种方式做到了这一点,但我不知道如何做。

有人知道我该怎么做吗?非常感谢。

最佳答案

您只能在调用函数时执行此操作,通常是使用 Function#callFunction#apply :

function foo() {
console.log("name = " + this.name);
}
var obj = {name: "Fred"};
foo.call(obj); // Outputs "Fred"

在那里,我们使用 call 调用 foo 函数,传入 obj 作为 this 使用的值> 在通话期间。

将其应用于 DOM 元素:

function foo() {
console.log("My id is " + this.id);
}
var elm = document.getElementById("whatever");
foo.call(elm); // "My id is whatever"

在调用期间用作this 的值是callapply 的第一个参数。两者之间的唯一区别是如何将参数传递给函数(foo,在我们上面的示例中):使用 call,您将它们作为后续离散参数传递:

theFunction.call(thisArg, firstArg, secondArg, thirdArg);

使用apply,你给它一个参数的数组:

var args = [firstArg, secondArg, thirdArg];
theFunction.apply(thisArg, args);

// or (of course)
theFunction.apply(thisArg, [firstArg, secondArg, thirdArg]);
// Note -------------------^-----------------------------^

所以一个更完整的例子:

function foo(firstArg, secondArg, thirdArg) {
console.log("name = " + this.name);
console.log("firstArg = " + firstArg);
console.log("secondArg = " + secondArg);
console.log("thirdArg = " + thirdArg);
}
var obj = {name: "Fred"};

// These two calls do exactly the same thing:
foo.call(obj, "one", "two", "three");
foo.apply(obj, ["one", "two", "three"]); // Note the [ and ]

关于JavaScript 库将其设置为一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com