javascript - 像选择器原型(prototype)这样的库中出现 'this' 的问题

标签 javascript function pipe this

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

  • 像上面提到的选择器,然后使用名为sample的函数对其进行原型(prototype)设计,并在其中调用一个函数
  • 如果用户使用“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)中并作为实用程序方法,但实用程序方法必须是包装器。
  • 如果原型(prototype)方法是这样的:

    $.prototype.foo = 函数(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 */]]

也许你想构建这样的东西:

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

关于javascript - 像选择器原型(prototype)这样的库中出现 'this' 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34851320/

相关文章:

javascript - 描述变量的对象属性

r - R中的函数参数定义问题

node.js - 如何等待流完成管道? ( Node )

io - 如何惯用/高效地将数据从 Read+Seek 传输到 Write?

javascript - 如何将从谷歌应用程序脚本 HTMLService 类获取的模板插入到 .html 文件中?

javascript - 如何在 Redux 中更新状态后触发关闭回调?

javascript - jQuery Animate 无限变换

javascript - AJAX/Javascript 功能不起作用

javascript - 覆盖函数类型原型(prototype)

Angular 2 : Set and remove custom pipes?