I'm kind of new to javascript. I'm so confused that javascript Objects!!
My code skeleton is bellow...
var jCanvas = new function(){
this.init = function(canvasID){
...
};
var DrawingManager = new function(){
drawInfos = []; // DrawInfo objects will be pushed into this
this.mouseState = MouseState.released;
...
};
function DrawInfo(bm, cl, id, x, y){
...
}
function Point(x, y){
...
}
var MouseState = new function(){
...
};
var Color = new function(){
...
};
var BrushMode = new function(){
...
};
};
I want jCanvas to be singleton class Object.
in jCanvas object, there are many singleton classes such as DrawingManager, MouseState, Color, BrushMode. And 2 more classes which are not singleton classes(Point, DrawInfo)
What I want is that, in DrawingManager, I want to access other classes and singleton class objects.
Problem is browser gives error that "MouseState is undefined".
I think I'm too familiar with Java, C# etc... I want my program to have good structure but this javascript make me so confused and don't know how to make good design pattern..
Please help me out..
To declare functions, don't use the new keyword. Only use it when creating instances of objects.
In JavaScript, you can declare a "class" like this (the body of the function is the constructor):
function MyClass (arg1) {
this.myClassProperty = arg1;
}
And then instantiate it:
var myObj = new MyClass();
If you want to create a singleton, the best method is to use an immediately invoked function:
var MySingleton = (function() {
var myPrivateFunction = function() { ... };
var myExportedFunction = function() { ... };
var myPrivateVar = 5;
return {
myExportedFunction: myExportedFunction
};
})();
Here, you create an anonymous function and immediately run it. It is kind of a more advanced concept though.
Or you can simply create an object:
var MySingleton = {
myProperty: 1,
myFunction: function() { ... },
...
};
Singleton classes in JavaScript make no sense. Either make a constructor ("class" for Java people) to instantiate multiple objects, or make an object. There is no point in making a constructor that you will only ever use once, then have the code to sanity-check whether or not you actually do use it only once. Just make an object.
The reason for the error is probably (but I might be wrong, I'm guessing about the rest of your code) the misunderstanding between var x = function ... and function name() ... forms. To whit:
var a = function() { console.log("a"); }
function b() { console.log("b"); }
a(); // a
b(); // b
c(); // c
d(); // TypeError: d is not a function
function c() { console.log("c"); }
var d = function() { console.log("d"); }
They are identical in effect, but they differ in whether they are hoisted to the top of the scope or not. var d is hoisted, just like function c() { ... } - so the variable d will exist, but will be undefined, since the assignment is not hoisted. Having both styles of function declarations is inconsistent unless you have a good reason for it; pick one of them and stick to it, is what I'd recommend.
Related
function Base(x) {
this.x = x;
this.sub = new (function Sub() {
this.method = function() {
return function() {**this.super.x**}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
var base = new Base(5);
console.log(base.sub.method()())
basically, in this example I'm trying to create an object Base who has a sub object sub, which has a 'method' that uses an anonymous function. The anonymous function needs the x but cannot take in any parameters..
Is there any way to access the this.x of Base?
At the beginning I tried the following.
This works well when Base is not inherited by other objects.
But in the following
"use strict";
function Base(x) {
var that = this;
this.sub = new (function Sub() {
this.method = function() {
return function() {
console.log(that); // displays Base *note[1]
return that.x;
}; // return an anonymous function that uses the outer x, but for reasons the anonymous function can't take parameters
}
});
}
function Other() {
Base.call(this); // why do I need to call Base.call(this) ?
this.setX = function(x) {this.x = x;}
}
Other.prototype = new Base();
var other = new Other();
other.setX(5);
console.log(other.sub.method()()); // otherwise undefined?
Base is extended by Other, after struggles I figured out I need to call Base.call(this); in order to make it works. Otherwise console.log(other.sub.method()()); will be undefined.
If I put a console.log(that) at *note[1], it will actually says the that is a Base object even though I construct it using var other = new Other(); I guess the problem would be solved if that is an Other object? What am I misunderstanding here?
My question is why do I need to call Base.call(this)? Why does it works after calling it? Is there any better solution to this situation?
If I understand you correctly you'd like Base to have a Sub and Sub is aware of the Base instance?
At the moment you're declaring the Sub type over and over again every time you create a Base, not the most effective way of doing it. Maybe try something like this:
function Sub(baseInstance){
this.baseInstance = baseInstance;
}
Sub.prototype.displayBaseX=function(){
console.log('base.x in sub:', this.baseInstance.x);
};
function Base(){
this.x = 22;
this.sub = new Sub(this);
}
You should not create an instance of Parent to set prototype of Child, use Object.create instead.
As for Parent.call(this, arguments) that is to re use the constructor function of Parent in Child when inheriting. More info about that can be found here: https://stackoverflow.com/a/16063711/1641941
The reason why your code doesn't work without Base.call(this); is because Base constructor defines and creates it's Sub type and instance. Not re using the Base constructor code when creating a Other type would cause the Other type not to have a Sub instance.
Constructor code deals with instance specific members and prototype can hold members that are shared by all instances. So usually behavior (functions) and a value for immutable default data members (numbers, string, boolean) can be found on the prototype.
I'm not exactly sure what you're end goal is here. But to solve your scope issue, this seems to work.
"use strict";
function Base(x) {
this.sub = new (function Sub(_this) {
this.method = (function(_this) {
return function() {
return _this.x;
};
})(_this);
})(this);
}
function Other() {
Base.call(this); // why do I need to call Base.call(this) ?
this.setX = function(x) {this.x = x;}
}
Other.prototype = new Base();
var other = new Other();
other.setX(5);
console.log(other.sub.method()); // otherwise undefined?
And a fiddle.
JavaScript can create a object in many ways.
I try the following code to avoid new keyword to create a new Object of Class A.
My question is that A.prototype.init() here is whether equals new A()? is this good for practice, and why?
function A(){
}
A.prototype.init=function(){
return this;
}
var a = A.prototype.init();
console.log(a);
var a1=new A();
console.log(a1);
jsfiddle
All you're doing is returning the A.prototype object. You're not really initializing anything, and you're not using the result.
console.log(A.prototype === A.prototype.init()); // true
So unless you have a particular use in mind, I'd say, no it's not a good practice.
Not sure exactly why you want to avoid new, but in any case, you can change your constructor so that it can be called with or without new and still behave like a constructor.
function A() {
var ths = Object.create(A.prototype);
ths.foo = "bar";
return ths;
}
Now it won't matter if you use new. You're going to get a new object that inherits from A.prototype no matter what.
You can still use an .init() method, but you might as well just put the logic in the constructor.
Furthermore, you can easily create a factory that takes care of that little bit of boilerplate code.
function Ctor(fn) {
return function() {
var ths = Object.create(fn.prototype);
fn.apply(ths, arguments);
return ths;
};
}
So now you'd create your constructor like this:
var A = Ctor(function() {
this.foo = "bar";
});
You can avoid new by encapsulating your code with the module pattern and returning a function that calls the constructor, in other words:
var A = (function ClassA() {
// Constructor
function A(prop) {
this.prop = prop; // instance property
this._init();
}
// Public methods
A.prototype = {
_init: function() {
}
};
// Mini factory to create new instances
return function(prop) {
return new A(prop); // well, only one `new`
};
}());
Now you can create new instances without new:
var a = A('foo'); //=> A { prop: "foo", init: function }
Usually you catch direct function calls with instanceof:
function MyConstructor (a, b, c) {
if (!(this instanceof MyConstructor)) {
return new MyConstructor(a, b, c);
}
// ...
}
but there is no good reason to avoid using new. Object.create and other alternatives can have a significant performance impact.
I thought scope chain would make the first "test = new test();" work, but it doesn't. why?
var tool = new Tool();
tool.init();
function Tool(){
var test;
function init(){
//does not work, undefined
test = new Test();
//does work
this.test=new Test();
console.log(test);
}
}
function Test(){
}
EDIT: by not working i mean, it says that test is 'undefined'
It's simple. Your Tool instance does not have a init method. The init function in your code is merely a local function of the Tool constructor. Tool instances do not inherit such functions.
If you want your Tool instances to have a init method, you can:
assign it as a method inside the constructor:
function Tool () {
this.init = function () { ... };
}
or assign it to Tool.prototype (outside of the constructor!):
Tool.prototype.init = function () { ... };
The second option performs better, since all instances share the same init function. (In the first option, each instance gets its own init function which is created during the constructor call.)
Are you trying to access test in the scope of Tool, or on the object returned by it? They are two different variables. I've labeled them A and B:
var tool = new Tool();
function Tool(){
var testA; // Private
this.init = function(){
testA = 1;
this.testB = 9; // Public
}
this.getTestA = function(){ // Public method to access the private testA
return testA;
}
}
tool.init();
console.log( tool.getTestA() ); // 1
console.log( tool.testB ); // 9
testA is known as a Private variable, only accessible through Tool's methods, while testB is public.
Does this cover what you're looking for?
By the way, if you're making a lot of instances of Tool, remember to use Tool's prototype to define the functions instead, so your code is more memory efficient, like so:
function Tool(){
var testA;
}
Tool.prototype.init = function(){
testA = 1;
this.testB = 9;
}
Tool.prototype.getTestA = function(){ return testA; }
I just read a few threads on the discussion of singleton design in javascript. I'm 100% new to the Design Pattern stuff but as I see since a Singleton by definition won't have the need to be instantiated, conceptually if it's not to be instantiated, in my opinion it doesn't have to be treated like conventional objects which are created from a blueprint(classes). So my wonder is why not just think of a singleton just as something statically available that is wrapped in some sort of scope and that should be all.
From the threads I saw, most of them make a singleton though traditional javascript
new function(){}
followed by making a pseudo constructor.
Well I just think an object literal is enough enough:
var singleton = {
dothis: function(){},
dothat: function(){}
}
right? Or anybody got better insights?
[update] : Again my point is why don't people just use a simpler way to make singletons in javascript as I showed in the second snippet, if there's an absolute reason please tell me. I'm usually afraid of this kind of situation that I simplify things to much :D
I agree with you, the simplest way is to use a object literal, but if you want private members, you could implement taking advantage of closures:
var myInstance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
About the new function(){} construct, it will simply use an anonymous function as a constructor function, the context inside that function will be a new object that will be returned.
Edit: In response to the #J5's comment, that is simple to do, actually I think that this can be a nice example for using a Lazy Function Definition pattern:
function singleton() {
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
When the function is called the first time, I make the object instance, and reassign singleton to a new function which has that object instance in it's closure.
Before the end of the first time call I execute the re-defined singleton function that will return the created instance.
Following calls to the singleton function will simply return the instance that is stored in it's closure, because the new function is the one that will be executed.
You can prove that by comparing the object returned:
singleton() == singleton(); // true
The == operator for objects will return true only if the object reference of both operands is the same, it will return false even if the objects are identical but they are two different instances:
({}) == ({}); // false
new Object() == new Object(); // false
I have used the second version (var singleton = {};) for everything from Firefox extensions to websites, and it works really well. One good idea is to not define things inside the curly brackets, but outside it using the name of the object, like so:
var singleton = {};
singleton.dothis = function(){
};
singleton.someVariable = 5;
The ES5 spec lets us use Object.create():
var SingletonClass = (function() {
var instance;
function SingletonClass() {
if (instance == null) {
instance = Object.create(SingletonClass.prototype);
}
return instance;
}
return {
getInstance: function() {
return new SingletonClass();
}
};
})();
var x = SingletonClass.getInstance();
var y = SingletonClass.getInstance();
var z = new x.constructor();
This is nice, since we don't have to worry about our constructor leaking, we still always end up with the same instance.
This structure also has the advantage that our Singleton doesn't construct itself until it is required. Additionally, using the closure as we do here prevents external code from using our "instance" variable, accidentally or otherwise. We can build more private variables in the same place and we can define anything we care to export publically on our class prototype.
The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. 1
(function (global) {
var singleton;
function Singleton () {
// singleton does have a constructor that should only be used once
this.foo = "bar";
delete Singleton; // disappear the constructor if you want
}
global.singleton = function () {
return singleton || (singleton = new Singleton());
};
})(window);
var s = singleton();
console.log(s.foo);
var y = singleton();
y.foo = "foo";
console.log(s.foo);
You don't just declare the singleton as an object because that instantiates it, it doesn't declare it. It also doesn't provide a mechanism for code that doesn't know about a previous reference to the singleton to retrieve it. The singleton is not the object/class that is returned by the singleton, it's a structure. This is similar to how closured variables are not closures, the function scope providing the closure is the closure.
I am just posting this answer for people who are looking for a reliable source.
according to patterns.dev by Lydia Hallie, Addy Osmani
Singletons are actually considered an anti-pattern, and can (or.. should) be avoided in JavaScript.
In many programming languages, such as Java or C++, it's not possible to directly create objects the way we can in JavaScript. In those object-oriented programming languages, we need to create a class, which creates an object. That created object has the value of the instance of the class, just like the value of instance in the JavaScript example.
Since we can directly create objects in JavaScript, we can simply use
a regular object to achieve the exact same result.
I've wondered about this too, but just defining an object with functions in it seems reasonable to me. No sense creating a constructor that nobody's ever supposed to call, to create an object with no prototype, when you can just define the object directly.
On the other hand, if you want your singleton to be an instance of some existing "class" -- that is, you want it to have some other object as its prototype -- then you do need to use a constructor function, so that you can set its prototype property before calling it.
The latter code box shows what I've seen JS devs call their version of OO design in Javascript.
Singetons are meant to be singular objects that can't be constructed (except, I suppose, in the initial definition. You have one, global instance of a singleton.
The point of using the "pseudo constructor" is that it creates a new variable scope. You can declare local variables inside the function that are available inside any nested functions but not from the global scope.
There are actually two ways of doing it. You can call the function with new like in your example, or just call the function directly. There are slight differences in how you would write the code, but they are essentially equivalent.
Your second example could be written like this:
var singleton = new function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
this.dothis = function () {
return privateVariable;
};
this.dothat = function () {};
}; // Parentheses are allowed, but not necessary unless you are passing parameters
or
var singleton = (function () {
var privateVariable = 42; // This can be accessed by dothis and dothat
return {
dothis: function () {
return privateVariable;
},
dothat: function () {}
};
})(); // Parentheses are required here since we are calling the function
You could also pass arguments to either function (you would need to add parentheses to the first example).
Crockford (seems to) agree that the object literal is all you need for a singleton in JavaScript:
http://webcache.googleusercontent.com/search?q=cache:-j5RwC92YU8J:www.crockford.com/codecamp/The%2520Good%2520Parts%2520ppt/5%2520functional.ppt+singleton+site:www.crockford.com&cd=1&hl=en&ct=clnk
How about this:
function Singleton() {
// ---------------
// Singleton part.
// ---------------
var _className = null;
var _globalScope = null;
if ( !(this instanceof arguments.callee) ) {
throw new Error("Constructor called as a function.");
}
if ( !(_className = arguments.callee.name) ) {
throw new Error("Unable to determine class name.")
}
_globalScope = (function(){return this;}).call(null);
if ( !_globalScope.singletons ) {
_globalScope.singletons = [];
}
if ( _globalScope.singletons[_className] ) {
return _globalScope.singletons[_className];
} else {
_globalScope.singletons[_className] = this;
}
// ------------
// Normal part.
// ------------
var _x = null;
this.setx = function(val) {
_x = val;
}; // setx()
this.getx = function() {
return _x;
}; // getx()
function _init() {
_x = 0; // Whatever initialisation here.
} // _init()
_init();
} // Singleton()
var p = new Singleton;
var q = new Singleton;
p.setx(15);
q.getx(); // returns 15
I stole this from CMS / CMS' answer, and changed it so it can be invoked as:
MySingleton.getInstance().publicMethod1();
With the slight alternation:
var MySingleton = { // These two lines
getInstance: function() { // These two lines
var instance = (function() {
var privateVar;
function privateMethod () {
// ...
console.log( "b" );
}
return { // public interface
publicMethod1: function () {
// private members can be accessed here
console.log( "a" );
},
publicMethod2: function () {
// ...
privateMethod();
}
};
})();
singleton = function () { // re-define the function for subsequent calls
return instance;
};
return singleton(); // call the new function
}
}
I'm trying to generate a class from an object in JavaScript. For example:
var Test = {
constructor: function() { document.writeln('test 1'); },
method: function() { document.writeln('test 2'); }
};
var TestImpl = function() { };
TestImpl.prototype.constructor = Test.constructor;
TestImpl.prototype.method = Test.method;
var x = new TestImpl();
x.method();
But this doesn't work: it'll only write 'test 2' (for whatever reason, constructor isn't being defined properly). Why?
I think you're doing it wrong.
Remember, JavaScript doesn't actually have classes at all. It has prototypes instead. So what you're really trying to do is create a prototype object that works like a collection of functions that you've built on another object. I can't imagine any useful purpose for this -- could you elaborate as to what you're trying to do?
Although I think you could make it work by using something like:
var TestImpl = function() {
Test.constructor.apply(this);
};
TestImpl.prototype.method = Test.method;
Your TestImpl function is the constructor. Usually you would do something like this:
var Test1 = function () {
document.writeln('in constructor');
};
Test1.prototype = {
x: 3,
method1: function() { document.writeln('x='+this.x); }
}
var y1 = new Test1();
y1.method1();
y1.x = 37;
y1.method1();
var y2 = new Test1();
y2.method1();
y2.x = 64;
y2.method1();
I think you have things a little backwards. Usually you will assign a prototype to a constructor, rather than assigning a constructor to a prototype.
The reason for assigning a method to the constructor's prototype, rather than to the "this" object inside the constructor, is that the former method creates only 1 shared function, whereas the latter method creates separate instances of a function. This is important (to keep memory allocation to a reasonable amount) if you create lots of objects each with lots of methods.
var Test = function () {
document.writeln('test 1');
this.method = function() { document.writeln('test 2'); }
};
var x = new Test();
x.method();
Javascript doesn't have a "Class" concept, It's all about prototype and the way you use them [ and you can simulate any kind of inheritance with this little neat feature. ]
In javascript "Function" plays the role of [ Class, Method and Constructor ].
so inorder to create "Class" behaviour in Javascript all you need to do is to use the power of "Function".
var A = function(){
alert('A.Constructor');
}
A.prototype = {
method : function(){
alert('A.Method');
}
}
var b = new A(); // alert('A.Constructor');
b.method(); // alert('A.Method');
now the neat thing about JS is that you can easily create "Inheritance" behaviour by using the same method. All you need to do is to connect the second class "Prototype Chain" to the first one, How?
B = function(){
this.prototype = new A(); // Connect "B"'s protoype to A's
}
B.prototype.newMethod = function() { alert('testing'); }
var b = new B();
b.method(); // Doesn't find it in B's prototype,
// goes up the chain to A's prototype
b.newMethod(); // Cool already in B's prototype
// Now when you change A, B's class would automatically change too
A.prototype.method = function(){ alert('bleh'); }
b.method(); // alert('bleh')
If you need any more references I suggest to take a look at Douglas Crockford's Site
Happy JS ing.