像选择器原型这样的库中的 'this' 问题

issues of 'this' in a library like selector prototype

我想做什么? $(arguments).sample(function(){ return 这个; })

我做了什么?

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();

您可以使用此代码段。

   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);
     }
   }
  • 如果参数是原语怎么办。这不可能是原语。+
  • 您可以将函数添加到原型并作为 utility-method,但 utility-method 必须是包装器。
  • 如果 proto-method 是这样的:

    $.prototype.foo = 函数(arg1, arg2, arg3){ 对于(var i=0;我

utility-method 的签名应该是什么?如何分离 "this" 和 function-args 的参数?

$.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 */]]

也许您想像这样构建某物:

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 $);