extend
can.Construct.extend([name,] [staticProperties,] instanceProperties)
Extends can.Construct
, or constructor functions derived from can.Construct
,
to create a new constructor function. Example:
var Animal = can.Construct.extend({
sayHi: function(){
console.log("hi")
}
})
var animal = new Animal()
animal.sayHi();
Parameters
-
name
{String}
OptionalCreates the necessary properties and objects that point from the
window
to the created constructor function. The following:can.Construct.extend("company.project.Constructor",{})
creates a
company
object on window if it does not find one, aproject
object oncompany
if it does not find one, and it will set theConstructor
property on theproject
object to point to the constructor function.Finally, it sets "company.project.Constructor" as fullName and "Constructor" as shortName.
-
staticProperties
{Object}
OptionalProperties that are added the constructor function directly. For example:
var Animal = can.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.
-
instanceProperties
{Object}
Properties that belong to instances made with the constructor. These properties are added to the constructor's
prototype
object. Example:var Animal = can.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!"
Returns
{function()}
The constructor function.
var Animal = can.Construct.extend(...);
var pony = new Animal(); // Animal is a constructor function
Inheritance
Creating "subclasses" with
can.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 ourSnake
to be anAnimal
, but there are some differences:Static properties and inheritance
If you pass all three arguments to can.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: