English 中文(简体)
共同提交文件:作为论据通过范围,使之具有被退回的职能
原标题:JS: Passing a scope as argument, binding it to a function that will be returned

是否可以界定母职职能的范围,并将通过母职职能通过的论点作为其范围加以约束,然后再将其退回?

例如:

var myObject = {
    foo: "bar"
};

var myFunction = (function() {
    return function() {
        return this.foo;
    };
}).call(myObject);

myFunction.call(myObject); // I d like to bind myObject as this does ...

myFunction(); // ... but I d like to do it before invoking it, without .call() or .apply()

或者另一个复杂的例子,它描述了我试图做些什么:

var createMyCopy = function(original, self) {
    var copy;

    eval("copy=" + original.toString());

    console.log(copy()); // returns undefined
};

(function() {
    var self = "Hello world",
        myFunction = function() {
            return self;
        };

    console.log(myFunction()); // returns "Hello world"

    createMyCopy(myFunction);
})();

我试图制作一份功能的复印件,以便我能够在不改动原有功能的情况下对功能作出改动,但我想有原功能中定义的变量。

最佳回答

你们是否同意这样做?

var myObject = {
    foo: "bar"
};

var myFunction = (function() {
    var self = this;
    return function() {
        return self.foo;
    };
}).call(myObject);

我认为,在你的问题中,你们重新获得了范围和背景。

问题回答

页: 1 这意味着:

var myFunction = (function(obj) {
    return function() {
        return obj.foo;
    };
})(myObject);

<立即援引功能表述<>>通过<条码>,,并将这一参数作为可变代码约束的新功能退回。

我不肯定你的含义,但你可以这样做:

var myObject = {
    foo: "bar"
};
function myFunction() {
    return this.foo;
}
console.log(myFunction.apply(myObject)); // bar

<编码>应用的第一个论点是context(参见this/code>。 “apply”的第二个论点是一系列论点(但我略去了,因为没有任何论点)。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.