选择器原型等库中的“这个”问题

issues of 'this' in a library like selector prototype

本文关键字:这个 问题 原型 选择器      更新时间:2023-09-26

我想做什么?$(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);
     }
   }
相关文章: