这个'的问题在像选择器原型的库中

时间:2016-01-18 09:32:16

标签: javascript function pipe this

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

  • 如上所述的选择器,然后使用名为sample的函数对其进行原型设计,并在该调用中使用函数
  • 如果用户使用'这个&#39 ;;应该返回参数对象

我做了什么?

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

2 个答案:

答案 0 :(得分:1)

  • 如果参数是原始的,那该怎么办?这不可能是原始的。+
  • 您可以将函数添加到原型中并作为实用程序方法添加,但实用程序方法必须是包装器。
  • 如果proto方法是这样的:

    $ .prototype.foo = function(arg1,arg2,arg3){     for(var i = 0; i

实用方法的签名应该是什么?如何分离“this”的args和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 $);

答案 1 :(得分:0)

您可以使用此代码段。

var colorArray = ["#14183b", "#002e2e", "#0d2d40", "#173052", "#194759", "#296b73"];

 var count = 0;

setInterval(function(){
    document.body.style.backgroundColor = colorArray[count];
    count++;
    if(count == colorArray.length) {
        count = 0;
    }
}, 1000);