W3cubDocs

/Dojo

dojo/_base/lang

Summary

This module defines Javascript language extensions.

See the dojo/_base/lang reference documentation for more information.

Properties

Methods

clone(src)

Defined by dojo/_base/lang

Clones objects (including DOM nodes) and all children. Warning: do not clone cyclic structures.

Parameter Type Description
src anything

The object to clone

Returns: anything | undefined | instance

The object to clone

delegate(obj,props)

Defined by dojo/_base/lang

Returns a new object which "looks" to obj for properties which it does not have a value for. Optionally takes a bag of properties to seed the returned object with initially.

This is a small implementation of the Boodman/Crockford delegation pattern in JavaScript. An intermediate object constructor mediates the prototype chain for the returned object, using it to delegate down to obj for property lookup when object-local lookup fails. This can be thought of similarly to ES4's "wrap", save that it does not act on types but rather on pure objects.

Parameter Type Description
obj Object

The object to delegate to for properties not found directly on the return object or in props.

props Object...

an object containing properties to assign to the returned object

Returns: any

an Object of anonymous type

Examples

Example 1

var foo = { bar: "baz" };
var thinger = lang.delegate(foo, { thud: "xyzzy"});
thinger.bar == "baz"; // delegated to foo
foo.thud == undefined; // by definition
thinger.thud == "xyzzy"; // mixed in from props
foo.bar = "thonk";
thinger.bar == "thonk"; // still delegated to foo's bar

exists(name,obj)

Defined by dojo/_base/lang

determine if an object supports a given method

useful for longer api chains where you have to test each object in the chain. Useful for object and method detection.

Parameter Type Description
name String

Path to an object, in the form "A.B.C".

obj Object
Optional

Object to use as root of path. Defaults to 'dojo.global'. Null may be passed.

Returns: boolean

Examples

Example 1

// define an object
var foo = {
      bar: { }
};

// search the global scope
lang.exists("foo.bar"); // true
lang.exists("foo.bar.baz"); // false

// search from a particular scope
lang.exists("bar", foo); // true
lang.exists("bar.baz", foo); // false

extend(ctor,props)

Defined by dojo/_base/lang

Adds all properties and methods of props to constructor's prototype, making them available to all instances created with constructor.

Parameter Type Description
ctor Object

Target constructor to extend.

props Object

One or more objects to mix into ctor.prototype

Returns: Object

Target constructor to extend.

getObject(name,create,context)

Defined by dojo/_base/lang

Get a property from a dot-separated string, such as "A.B.C"

Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format.

Parameter Type Description
name String

Path to an property, in the form "A.B.C".

create Boolean
Optional

Optional. Defaults to false. If true, Objects will be created at any point along the 'path' that is undefined.

context Object
Optional

Optional. Object to use as root of path. Defaults to 'dojo.global'. Null may be passed.

Returns: undefined

hitch(scope,method)

Defined by dojo/_base/lang

Returns a function that will only ever execute in the given scope. This allows for easy use of object member functions in callbacks and other places in which the "this" keyword may otherwise not reference the expected scope. Any number of default positional arguments may be passed as parameters beyond "method". Each of these values will be used to "placehold" (similar to curry) for the hitched function.

Parameter Type Description
scope Object

The scope to use when method executes. If method is a string, scope is also the object containing method.

method Function | String...

A function to be hitched to scope, or the name of the method in scope to be hitched.

Returns: undefined | function

Examples

Example 1

lang.hitch(foo, "bar")();

runs foo.bar() in the scope of foo

Example 2

lang.hitch(foo, myFunction);

returns a function that runs myFunction in the scope of foo

Example 3

Expansion on the default positional arguments passed along from hitch. Passed args are mixed first, additional args after.

var foo = { bar: function(a, b, c){ console.log(a, b, c); } };
var fn = lang.hitch(foo, "bar", 1, 2);
fn(3); // logs "1, 2, 3"

Example 4

var foo = { bar: 2 };
lang.hitch(foo, function(){ this.bar = 10; })();

execute an anonymous function in scope of foo

isAlien(it)

Defined by dojo/_base/lang

Returns true if it is a built-in function or some other kind of oddball that should report as a function but doesn't

Parameter Type Description
it undefined

Returns: undefined

isArray(it)

Defined by dojo/_base/lang

Return true if it is an Array. Does not work on Arrays created in other windows.

Parameter Type Description
it anything

Item to test.

Returns: undefined

isArrayLike(it)

Defined by dojo/_base/lang

similar to isArray() but more permissive

Doesn't strongly test for "arrayness". Instead, settles for "isn't a string or number and has a length property". Arguments objects and DOM collections will return true when passed to isArrayLike(), but will return false when passed to isArray().

Parameter Type Description
it anything

Item to test.

Returns: any | Boolean

If it walks like a duck and quacks like a duck, return true

isFunction(it)

Defined by dojo/_base/lang

Return true if it is a Function

Parameter Type Description
it anything

Item to test.

Returns: boolean

isObject(it)

Defined by dojo/_base/lang

Returns true if it is a JavaScript object (or an Array, a Function or null)

Parameter Type Description
it anything

Item to test.

Returns: boolean

isString(it)

Defined by dojo/_base/lang

Return true if it is a String

Parameter Type Description
it anything

Item to test.

Returns: boolean

mixin(dest,sources)

Defined by dojo/_base/lang

Copies/adds all properties of one or more sources to dest; returns dest.

All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions found in Object.prototype, are copied/added from sources to dest. sources are processed left to right. The Javascript assignment operator is used to copy/add each property; therefore, by default, mixin executes a so-called "shallow copy" and aggregate types are copied/added by reference.

Parameter Type Description
dest Object

The object to which to copy/add all properties contained in source. If dest is falsy, then a new object is manufactured before copying/adding properties begins.

sources Object...

One of more objects from which to draw all properties to copy into dest. sources are processed left-to-right and if more than one of these objects contain the same property name, the right-most value "wins".

Returns: Object | object

dest, as modified

Examples

Example 1

make a shallow copy of an object

var copy = lang.mixin({}, source);

Example 2

many class constructors often take an object which specifies values to be configured on the object. In this case, it is often simplest to call lang.mixin on the this object:

declare("acme.Base", null, {
    constructor: function(properties){
        // property configuration:
        lang.mixin(this, properties);

        console.log(this.quip);
        //  ...
    },
    quip: "I wasn't born yesterday, you know - I've seen movies.",
    // ...
});

// create an instance of the class and configure it
var b = new acme.Base({quip: "That's what it does!" });

Example 3

copy in properties from multiple objects

var flattened = lang.mixin(
    {
        name: "Frylock",
        braces: true
    },
    {
        name: "Carl Brutanananadilewski"
    }
);

// will print "Carl Brutanananadilewski"
console.log(flattened.name);
// will print "true"
console.log(flattened.braces);

partial(method)

Defined by dojo/_base/lang

similar to hitch() except that the scope object is left to be whatever the execution context eventually becomes.

Calling lang.partial is the functional equivalent of calling:

lang.hitch(null, funcName, ...);
Parameter Type Description
method Function | String

The function to "wrap"

Returns: undefined

replace(tmpl,map,pattern)

Defined by dojo/_base/lang

Performs parameterized substitutions on a string. Throws an exception if any parameter is unmatched.

Parameter Type Description
tmpl String

String to be used as a template.

map Object | Function

If an object, it is used as a dictionary to look up substitutions. If a function, it is called for every substitution with following parameters: a whole match, a name, an offset, and the whole template string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace for more details).

pattern RegEx
Optional

Optional regular expression objects that overrides the default pattern. Must be global and match one item. The default is: /{([^}]+)}/g, which matches patterns like that: "{xxx}", where "xxx" is any sequence of characters, which doesn't include "}".

Returns: String | undefined

Returns the substituted string.

Examples

Example 1

// uses a dictionary for substitutions:
lang.replace("Hello, {name.first} {name.last} AKA {nick}!",
    {
        nick: "Bob",
        name: {
            first:  "Robert",
            middle: "X",
            last:       "Cringely"
        }
    });
// returns: Hello, Robert Cringely AKA Bob!

Example 2

// uses an array for substitutions:
lang.replace("Hello, {0} {2}!",
    ["Robert", "X", "Cringely"]);
// returns: Hello, Robert Cringely!

Example 3

// uses a function for substitutions:
function sum(a){
    var t = 0;
    arrayforEach(a, function(x){ t += x; });
    return t;
}
lang.replace(
    "{count} payments averaging {avg} USD per payment.",
    lang.hitch(
        { payments: [11, 16, 12] },
        function(_, key){
            switch(key){
                case "count": return this.payments.length;
                case "min":     return Math.min.apply(Math, this.payments);
                case "max":     return Math.max.apply(Math, this.payments);
                case "sum":     return sum(this.payments);
                case "avg":     return sum(this.payments) / this.payments.length;
            }
        }
    )
);
// prints: 3 payments averaging 13 USD per payment.

Example 4

// uses an alternative PHP-like pattern for substitutions:
lang.replace("Hello, ${0} ${2}!",
    ["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
// returns: Hello, Robert Cringely!

setObject(name,value,context)

Defined by dojo/_base/lang

Set a property from a dot-separated string, such as "A.B.C"

Useful for longer api chains where you have to test each object in the chain, or when you have an object reference in string format. Objects are created as needed along path. Returns the passed value if setting is successful or undefined if not.

Parameter Type Description
name String

Path to a property, in the form "A.B.C".

value anything

value or object to place at location given by name

context Object
Optional

Optional. Object to use as root of path. Defaults to dojo.global.

Returns: undefined

Examples

Example 1

set the value of foo.bar.baz, regardless of whether intermediate objects already exist:

lang.setObject("foo.bar.baz", value);

Example 2

without lang.setObject, we often see code like this:

// ensure that intermediate objects are available
if(!obj["parent"]){ obj.parent = {}; }
if(!obj.parent["child"]){ obj.parent.child = {}; }
// now we can safely set the property
obj.parent.child.prop = "some value";

whereas with lang.setObject, we can shorten that to:

lang.setObject("parent.child.prop", "some value", obj);

trim(str)

Defined by dojo/_base/lang

Trims whitespace from both sides of the string

This version of trim() was selected for inclusion into the base due to its compact size and relatively good performance (see Steven Levithan's blog Uses String.prototype.trim instead, if available. The fastest but longest version of this function is located at lang.string.trim()

Parameter Type Description
str String

String to be trimmed

Returns: String

Returns the trimmed string

© 2005–2017 JS Foundation
Licensed under the AFL 2.1 and BSD 3-Clause licenses.
http://dojotoolkit.org/api/1.10/dojo/_base/lang.html