The object constructor function is a standard way to create an instance of an Object class in JavaScript. An object constructor is just a regular JavaScript function and it is robust enough to define properties, invoke other functions, and do much more. To create an instance of the object, we need to call the object constructor function via a new
operator. Let's have a look at the next JavaScript code:
function Engine(type) { this.type = type; this.start = function() { console.log ('Started ' + type + ' engine'), }; };
Engine
is an object constructor function. It has a type
property and a start
method. Here is how we can create an instance of the JavaScript object from Dart:
import 'dart:js' as js; void main() { js.JsFunction JsEngine = js.context['Engine']; js.JsObject engineObj = new js.JsObject(JsEngine, ['diesel']); assert(engineObj.instanceof(JsEngine)); engineObj.callMethod('start'), }
We created a JsFunction
variable, JsEngine
, as a reference to the JavaScript object constructor function Engine
. To create an object type engineObj
, we used an object constructor created via the JsObject
proxy. The function arguments must be sent via a second parameter, so we specified diesel
as the engine type. Later, we check whether engineObj
is an instance of the JsEngine
type. Finally, we call the start
method from engineObj
and it prints the following message on the console:
Started diesel engine
If you select the
JsEngine
property in the variable inspector of the Dart Editor when the breakpoint is reached, you will see the source code of the JavaScript function, as shown in the following screenshot:
3.144.113.163