Search code examples
javascriptoopjavascript-objectsnativescript

Javascript class/ function in Nativescript


I am trying to move some common logic from multiple of my models in NativeScript to one seperate file that I want to require in my models. I don't have any Javascript experience and wanted to make a class like you'd do in Java however this appearantly doesn't work.

Can anybody explain what goes wrong and how I'd have to go about this?

This is what I currently have (example code):

CommonLogic.js

function Person(lastName, firstName)
{
   this.firstName = firstName;
   this.lastName = lastName;
}

Model1.js

var Person = require("~/CommonLogic");

exports.loaded = function(args) {  
    var person = new Person('Clouseau', 'Jacques');
    console.log('The person is ' + person);
}

Error:

System.err: Calling js method onCreateView failed
System.err:
System.err: TypeError: Person is not a constructor

Solution

  • When you created the below function

    function Person(lastName, firstName)
    {
       this.firstName = firstName;
       this.lastName = lastName;
    }
    

    And then you tried to import it like below

    var Person = require("~/CommonLogic");
    

    Now image you had another class in your code Person2

    function Person2(lastName, firstName)
    {
       this.firstName = firstName;
       this.lastName = lastName;
    }
    

    So, now how do you import this? Would doing var Person2 = require("~/CommonLogic"); import it Person2? That is not the way module require works. Now there are two ways to export a class/method. The ES5 way or the ES6 way

    ES5 way

    function Person(lastName, firstName)
    {
       this.firstName = firstName;
       this.lastName = lastName;
    }
    
    module.exports = { Person: Person}
    

    And then you can use the same in your scripts like below

    var Person = require("~/commonlogic").Person;
    

    ES6 Way

    ES6 has a export keyword. So you would just do

    export function Person(lastName, firstName)
    {
       this.firstName = firstName;
       this.lastName = lastName;
    }
    

    And import could be again either ES5 or ES6

    ES5 like below

    var Person = require("~/commonlogic").Person;
    

    ES6 like below

    import {Person} from '~/commonlogic';