I am using Google Closure and am trying to do something like below:
abc.edf.commands.showToast = function() {
abc.edf.commands.showToast.test(); // this works fine
this.test2(); // this will throw an error like:
// exception_logger.js:88 TypeError: this.test2 is not a function
};
abc.edf.commands.showToast.test = function() {
console.log('test');
};
abc.edf.commands.showToast.prototype.test2 = function() {
console.log('test2');
};
I think every object in JavaScript has 'prototype'. So is it because 'command' is not an object? Or I missed something else? Thanks :)
As Felix Kling commented you need to use new
to create an object in order to use the test2
prototype function. Here is an example:
goog.provide('abc.edf.commands.showToast');
/** @constructor */
abc.edf.commands.showToast = function() {};
abc.edf.commands.showToast.test = function() {
console.log('test');
};
abc.edf.commands.showToast.prototype.test2 = function() {
console.log('test2');
};
abc.edf.commands.showToast.test(); // static class method
var foo = new abc.edf.commands.showToast();
foo.test2(); // instance method
You can try entering that code in the online closure compiler. Here is what it compiles to using simple compile:
var abc={edf:{}};
abc.edf.commands={};
abc.edf.commands.showToast=function(){};
abc.edf.commands.showToast.test=function(){console.log("test")};
abc.edf.commands.showToast.prototype.test2=function(){console.log("test2")};
abc.edf.commands.showToast.test();
var foo=new abc.edf.commands.showToast;
foo.test2();
Here is what it compiles to using advanced compile:
console.log("test");
console.log("test2");
To test, I saved the compiled code to a file "showToast.js" and made a simple html page that loads it:
<!doctype html>
<html>
<head>
</head>
<body>
<p>ShowToast Test</p>
<script src="showToast.js"></script>
</body>
</html>