选择器原型等库中的“这个”问题
issues of 'this' in a library like selector prototype
我想做什么?$(arguments).sample(function(){ return this; })
- 上面提到的选择器,然后使用名为 sample 的函数对其进行原型设计,并在该函数中调用一个函数
- 如果用户使用"this";则应返回参数对象
我做了什么?
var $ = function(){
return new library();
}
var library = function(){};
library.prototype = {
sample: function(callback) {
callback();
}
}
但实际上无法做我想做的事情:/我尝试了很多东西,但我希望 $ 既可以用作函数$([1,2]).stringify()
(我一直在谈论),也可以用作上面提到的对象$.sample()
一些可能的例子:
$('hello').print();
$('hello').sample(function(){ console.log(this); });
$.print('hello');
$('hello').print().log();
- 如果参数是基元怎么办。 这不可能是基元+。
- 您可以将函数添加到原型中并作为实用程序方法,但实用程序方法必须是包装器。
-
如果原型方法是这样的
:$.prototype.foo = function(arg1, arg2, arg3){ for(var i=0; i
实用程序方法的签名应该是什么? 如何区分"this"和函数参数?
$.foo = function(...thisArg, arg1, arg2, arg3){}
//or
$.foo = function(thisArgs, arg1, arg2, arg3){}
//and what if thisArgs contains only one Array, are you sure, that you will remember/want to use [[/* values */]]
也许你想像这样构建 sth:
function $(){
var me = Object.create($.prototype);
for(var i=0, j=arguments.length; i<j; ++i) me[i] = arguments[i];
me.length = j;
//Object.freeze(me);
return me;
}
var AP = [];
$.prototype.reduce = AP.reduce;
$.prototype.each = function(fn){
AP.forEach.call(this, fn, this);
return this;
}
$.prototype.map = function(fn){
return $.apply(null, AP.map.call(this, fn, this));
}
$.prototype.filter = function(fn){
return $.apply(null, AP.filter.call(this, fn, this));
}
$.prototype.log = function(comment){
if(comment) console.log(comment + ":");
return this.each(v=>console.log(" ", v));
}
和用法
var a = $("lorem", "ipsum", "dolor");
a.map((v,i) => i + ": " + v).log("logged Items");
console.log("a instanceof $: ", a instanceof $);
您可以使用
此代码段。
var library = {
sample: function(callback) {
callback();
}
};
var $ = function(){
return library;
};
for (var method in library) {
if (library.hasOwnProperty(method) && typeof library[method] == 'function') {
$[method] = library[method].bind(library);
}
}
相关文章:
- 我该如何解决这个问题?“未捕获的类型错误:无法读取 null 的属性'appendChild'”
- MathJax正在复制我的方程式——为什么以及如何解决这个问题
- 我该如何解决这个问题;参考网格”;在JavaScript中完成的对象数
- Heroku 部分不提供我的一些图像,以前有人遇到过这个问题
- 代码不起作用.我无法确定这个问题
- .NET服务中的JSON反序列化-can'不能解决这个问题
- 对表演和隐藏有一些问题.如何解决这个问题
- Javascript计数器的增量超过1.为什么?我该如何解决这个问题
- Javascript逻辑运算符||将0读取为假值.有什么好办法解决这个问题吗
- 了解使用AngularJS承诺,他们将如何帮助解决这个问题
- JavaScript 循环输出顺序不正确 - 如何解决这个问题
- Jquery 选项卡在 Jcarousel 中不起作用.我该如何解决这个问题
- 如何在回调函数的 Angular 1.5 组件中处理这个问题
- Ajax 异步调用 - 如何克服这个问题
- 不知道如何问这个问题,但他们在这里想做什么
- 将“按$index跟踪”与过滤器一起使用时,出现错误.如何解决这个问题
- 我收到一个错误:类型错误:在使用解析 API 更新用户对象时未定义 e.changes.如何解决这个问题
- 将内联 Javascript 移动到外部文件时出错 - 我该如何解决这个问题
- 从手机禁用悬停的脚本是打开自窗口上的链接,我该如何解决这个问题
- 当您检查时,引导按钮类重复,我怎么能解决这个问题