简体   繁体   中英

Javascript: Prototype on a function which accepts an argument

I'm having trouble achieving something in Javascript, and also having trouble explaining it. I'm writing an API and I want the developer to be able to write the following code: dashboard('name1').createPanel('name2');

The problem is I can't figure out a way to create a function called "dashboard" (which accepts an argument 'name1') while also providing a prototype called createPanel.

You have functions and object. An example:

 // A normal function
 function dashboard(name) {

 }
 dashboard("name1");

You can also prototype this function if you do a new you will have to object of class dashboard. So the example:

function dashboard( name ) {
    // As class
    this.name = name;
}

dashboard.Prototype.createPanel = function(name) {
    this.name = name;
    return this;  // return the reference
}

var x = new dashboard("name1"); // create object
x.createPanel( "Name2" );

// x.name will be "Name2"

What you want is chaining functions. All you need to do is return the object where you want to call the next function from. If you return this every time you can chain functions of that object like:

// extending the class with addProperty for chainging example

dashboard.Prototype.addProperty = function(key, value){
    this[key] = value;
    return this; // To enable chaining, return reference
} 
var x = new dashboard("name1");
x.createPanel("Niels").addProperty("A", "B").addProperty("B", "C");

We can chain on and on. All you need to do is return the reference where you want to continue chaining from (normally the this object). But can be every object you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM