DoneJS StealJS jQuery++ FuncUnit DocumentJS
4.3.0
5.0.0 3.13.1 2.3.35
  • About
  • Guides
  • API Docs
  • Community
  • Contributing
  • Bitovi
    • Bitovi.com
    • Blog
    • Design
    • Development
    • Training
    • Open Source
    • About
    • Contact Us
  • About
  • Guides
  • API Docs
    • Observables
      • can-bind
      • can-compute
      • can-debug
      • can-define
      • can-define/list/list
      • can-define/map/map
      • can-define-backup
      • can-define-stream
      • can-define-stream-kefir
      • can-event-queue
      • can-kefir
      • can-list
      • can-map
      • can-map-define
      • can-observation
      • can-observation-recorder
      • can-observe
      • can-simple-map
      • can-simple-observable
      • can-stream
      • can-stream-kefir
      • can-value
    • Data Modeling
      • can-connect
      • can-connect-feathers
      • can-fixture
      • can-fixture-socket
      • can-ndjson-stream
      • can-set
    • Views
      • can-component
      • can-stache
      • can-stache-bindings
      • can-stache-converters
      • can-stache-route-helpers
      • can-view-autorender
      • can-view-callbacks
      • can-view-import
      • can-view-live
      • can-view-model
      • can-view-nodelist
      • can-view-parser
      • can-view-scope
      • can-view-target
      • react-view-model
      • react-view-model/component
      • steal-stache
    • Routing
      • can-deparam
      • can-param
      • can-route
      • can-route-hash
      • can-route-mock
      • can-route-pushstate
    • JS Utilities
      • can-assign
      • can-define-lazy-value
      • can-diff
      • can-globals
      • can-join-uris
      • can-key
      • can-key-tree
      • can-make-map
      • can-parse-uri
      • can-queues
      • can-string
      • can-string-to-any
      • can-util
      • can-zone
      • can-zone-storage
    • DOM Utilities
      • can-ajax
      • can-attribute-encoder
      • can-child-nodes
      • can-control
      • can-dom-data
      • can-dom-events
      • can-dom-mutate
      • can-event-dom-enter
      • can-event-dom-radiochange
      • can-fragment
    • Data Validation
      • can-define-validate-validatejs
      • can-validate
      • can-validate-interface
      • can-validate-legacy
      • can-validate-validatejs
    • Typed Data
      • can-cid
      • can-construct
        • prototype
          • constructor
          • init
          • setup
        • static
          • ReturnValue
          • constructorExtends
          • extend
          • newInstance
          • setup
          • shortName
      • can-construct-super
      • can-data-types
      • can-namespace
      • can-reflect
      • can-reflect-dependencies
      • can-reflect-promise
      • can-types
    • Polyfills
      • can-symbol
      • can-vdom
    • Core
    • Infrastructure
      • can-global
      • can-test-helpers
    • Ecosystem
    • Legacy
  • Community
  • Contributing
  • GitHub
  • Twitter
  • Chat
  • Forum
  • News
Bitovi

extend

  • Edit on GitHub

Construct.extend([name,] [staticProperties,] instanceProperties)

Extends Construct, or constructor functions derived from Construct, to create a new constructor function. Example:

var Animal = Construct.extend({
  sayHi: function(){
    console.log("hi")
  }
});

var animal = new Animal()
animal.sayHi();

Parameters

  1. name {String}:

    Adds a name to the constructor function so it is nicely labeled in the developer tools. The following:

    Construct.extend("ConstructorName",{})
    

    returns a constructur function that will show up as ConstructorName in the developer tools. It also sets "ConstructorName" as shortName.

  2. staticProperties {Object}:

    Properties that are added the constructor function directly. For example:

    var Animal = Construct.extend({
      findAll: function(){
        return can.ajax({url: "/animals"})
      }
    },{}); // need to pass an empty instanceProperties object
    
    Animal.findAll().then(function(json){ ... })
    

    The static setup method can be used to specify inheritable behavior when a Constructor function is created.

  3. instanceProperties {Object}:

    Properties that belong to instances made with the constructor. These properties are added to the constructor's prototype object. Example:

    var Animal = Construct.extend({
      findAll: function() {
        return can.ajax({url: "/animals"});
      }
    },{
      init: function(name) {
        this.name = name;
      },
      sayHi: function() {
        console.log(this.name," says hai!");
      }
    })
    var pony = new Animal("Gertrude");
    pony.sayHi(); // "Gertrude says hai!"
    

    The init and setup properties are used for initialization.

Returns

{function}:

The constructor function.

var Animal = Construct.extend(...);
var pony = new Animal(); // Animal is a constructor function

Inheritance

Creating "subclasses" with Construct is simple. All you need to do is call the base constructor with the new function's static and instance properties. For example, we want our Snake to be an Animal, but there are some differences:

var Snake = Animal.extend({
    legs: 0
}, {
    init: function() {
        Animal.prototype.init.call(this, 'ssssss');
    },
    slither: function() {
        console.log('slithering...');
    }
});

var baslisk = new Snake();
baslisk.speak();   // "ssssss"
baslisk.slither(); // "slithering..."
baslisk instanceof Snake;  // true
baslisk instanceof Animal; // true

Static properties and inheritance

If you pass all three arguments to Construct, the second one will be attached directy to the constructor, allowing you to imitate static properties and functions. You can access these properties through the this.constructor property.

Static properties can get overridden through inheritance just like instance properties. In the example below, we override both the legs static property as well as the the init function for each instance:

var Animal = Construct.extend({
    legs: 4
}, {
    init: function(sound) {
        this.sound = sound;
    },
    speak: function() {
        console.log(this.sound);
    }
});

var Snake = Animal.extend({
    legs: 0
}, {
    init: function() {
        this.sound = 'ssssss';
    },
    slither: function() {
        console.log('slithering...');
    }
});

Animal.legs; // 4
Snake.legs; // 0
var dog = new Animal('woof');
var blackMamba = new Snake();
dog.speak(); // 'woof'
blackMamba.speak(); // 'ssssss'

Alternative value for a new instance

Sometimes you may want to return some custom value instead of a new object when creating an instance of your class. For example, you want your class to act as a singleton, or check whether an item with the given id was already created and return an existing one from your cache store (e.g. using constructor/store).

To achieve this you can return ReturnValue from setup method of your class.

Lets say you have myStore to cache all newly created instances. And if an item already exists you want to merge the new data into the existing instance and return the updated instance.

var myStore = {};

var Item = Construct.extend({
    setup: function(params){
        if (myStore[params.id]){
            var item = myStore[params.id];

            // Merge new data to the existing instance:
            Object.assign(item, params);

            // Return the updated item:
            return new Construct.ReturnValue( item );
        } else {
            // Save to cache store:
            myStore[this.id] = this;

            return [params];
        }
    },
    init: function(params){
        Object.assign(this, params);
    }
});

var item_1  = new Item( {id: 1, name: "One"} );
var item_1a = new Item( {id: 1, name: "OnePlus"} )

CanJS is part of DoneJS. Created and maintained by the core DoneJS team and Bitovi. Currently 4.3.0.

On this page

Get help

  • Chat with us
  • File an issue
  • Ask questions
  • Read latest news