I have a javascript getter method like so:
function passTags()
{
var tags = document.getElementById('tags').value;
this.getTag=function()
{
return this.tags;
}
}
How do i call it?
Looks like you've set up a constructor function, so it would be like so
var t = new passTags;
t.getTag();
this.tags is not defined though, so t.getTag() will return undefined. If you meant for it to return the value of tags then change it to
function passTags() {
var tags = document.getElementById('tags').value;
this.getTag = function() {
return tags;
}
}
bear in mind though that the value captured will not update once the constructor function has executed, as this example will demonstrate. One more recommendation would be to use Pascal case for the function name so that it is clear that it is a constructor function.
The way that you have your code set up at the moment though, if it wasn't intended to be a constructor function then you would first have to execute passTags function. This would define a function in global scope, getTag, that could then be executed. This will return undefined however as this.tags is undefined.
You shouldn't define tags as var tags = ... but as this.tags = ...
-- edit
Russ's solution is 'better': tags is now private.
Related
Background
I want a function keeping track of its own state:
var myObject = {
myFunction: function () {
var myself = this.myFunction;
var firstTime = Boolean(!myself.lastRetry);
if (firstTime) {
myself.lastRetry = Date.now();
return true;
}
// some more code
}
}
The problem with the above code is that the value of this will depend on the site of the function call. I want the function to be able to refer to itself without using:
myObject.myFunction
.bind()
.apply()
.call()
Question
Is it possible to give a function this kind of self awareness independent of its call site and without any help from external references to it?
If you want to store that state on the function instance, give the function a name, and use that name within it:
var myObject = {
myFunction: function theFunctionName() {
// ^^^^^^^^^^^^^^^--------------------- name
var firstTime = Boolean(!theFunctionName.lastRetry);
// ^--------------------------- using it
if (firstTime) {
theFunctionName.lastRetry = Date.now();
// ^------------------------------------------------ using it
return true;
}
// some more code
}
};
You'd do that whenever you want to use a function recursively as well. When you give a name to a function that way (putting the name after function and before (), that name is in-scope within the function's own code. (It's not in-scope for the code containing the function if it's a function expression, but it is if it's a function declaration. Yours is an expression.)
That's a named function expression (where previously you had an anonymous function expression). You may hear warnings about NFEs, but the issues various JavaScript implementations had with them are essentially in the past. (IE8 still handles them incorrectly, though: More in this post on my blog.)
You might consider keeping that state somewhere private, though, via an IIFE:
var myObject = (function(){
var lastRetry = null;
return {
myFunction: function() {
var firstTime = Boolean(!lastRetry);
if (firstTime) {
lastRetry = Date.now();
return true;
}
// some more code
}
};
})();
Now, nothing outside that outer anonymous function can see lastRetry at all. (And you don't have to worry about IE8, if you're supporting stubborn XP users. :-) )
Side note: The unary ! operator always returns a boolean, so your
var firstTime = Boolean(!theFunctionName.lastRetry);
...is exactly equivalent to:
var firstTime = !theFunctionName.lastRetry;
...but with an extra unnecessary function call. (Not that it hurts anything.)
Of course you can, simply give your function an internal named representation and it can refer to itself from there. For example...
var obj = {
doThings:function doThingsInternal(arg1, arg2) {
console.log(arg1, arg2);
for (var arg in doThingsInternal.arguments) {
console.log(arg);
}
}
};
obj.doThings('John', 'Doe');
You could use a simple Closure, if you are not too bent on keeping state existence knowledge within the function. But I guess you don't want that. Another way to do this could be changing the function itself on the first call. Benefits, no/less state variables needed and no costly checks on subsequent calls! -
var myObject = {
myFunction: function () {
// Whatever you wanna do on the first call...
// ...
// And then...
this.myFunction = function(){
// Change the definition to whatever it should do
// in the subsequent calls.
}
// return the first call value.
}
};
You can extend this model to any states by changing the function definition per your state.
function abc(){
//multiple variables and functions
a:function(){alert("a")};
}
function test(){
var k=abc();
k.a();
}
In the above case, I have a huge function abc() to be assigned to a variable. I want to call the member functions that are visible, like a() from the variable. Is this possible to implement and please give me a sample code if so.
When you include the parenthesis after your function, you're assigning the result of the function to your variable.
If you want to assign the function itself, just omit the parenthesis:
var k = abc;
k.a();
EDIT
Per #Kuba Wyrostek's answer, and #Pointy's comment, that a() function won't be properly exposed.
You'll need to take a look at the Module Pattern. What you need to do is to assign a function to a variable, and have that function return the functions that you want to be able to use outside of that function. This helps with encapsulation.
It's a little hard to tell from your code in the comment exactly what is the user-generated code, but I'll do my best.
var abc = (function () {
var grabApi,
initialize;
// Just an example of how to assign an existing function
// to a property that will be exposed.
grabApi = SCORM2004_GrabAPI();
// This is an example of how to have a property that will be
// exposed be a custom function passing a parameter.
initialize = function(initString) {
return SCORM2004_GrabAPI().Initialize(initString);
};
return {
getApi: grabApi,
init: initialize
}
}());
You can then use this abc object like this throughout your code. Again, this is trying to give an example of how to do what I think you're trying to do based on your comment.
// Assign the SCORM2004_GrabAPI function to a variable.
var SCORM2004_objAPI = abc.getApi();
// Call the Initialize function with an empty string.
abc.init("");
Hmmm… contrary to #krillgar's answer, I believe you were expecting your abc() to return new object. Something like this:
function abc(){
var privateVar;
return {
//multiple variables and functions
a:function(){alert("a")}
}
}
function test(){
var k=abc();
k.a();
}
You should make it an object. In this way you can access its property a.
var abc ={
a:function(){alert("a")}
}
function test(){
var k=abc;//Ofcrse remove the parenthesis
k.a();
}
test();
I recently search in the code of the library of knockout to find how observables are able to create dependencies with computed functions when we call it.
In the source code, I found the function linked to observables creation:
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if (observable.isDifferent(_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return _latestValue;
}
}
ko.subscribable.call(observable);
ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
if (DEBUG) observable._latestValue = _latestValue;
observable.peek = function() { return _latestValue };
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
ko.exportProperty(observable, 'peek', observable.peek);
ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
return observable;
}
What I think is very weird is the returns of 'observable' where I don't found any declaration of this variable. Sure that great men who created this library don't forget to declared it.
How it is possible to use a variable without declared it and prevent it to be put in a global scope?
My feeling is we can used a function declaration as a variable when this function declaration is declared inside another function but I'm really not sure about how it works.
Edit:
After searching on the web, I found this article.
In this article, the guy write this:
Use declarations, please
"In the code of unexperienced developers, functions are often declared by expressions:
... code ... var f = function() { ... } ...
Function Declarations are much more readable and shorter. Use them instead.
... code ... function f() { ... } ...
Besides, functions declared this way can be called before it’s definition.
Use expressions only if you mean it. E.g for conditional function definition."
Ok, Am I an unexperienced developer? I don't think so. I just don't read all the odds of Javascript. :)
observable is a variable. It is declared by a function declaration.
function observable() {
...
}
In Javascript, functions can also be returned. Within the function, he defines the function "observable" which is returned at the end of the function.
Sort to speak, functions are variables too. With a function inside.
Why does the marked line fail to find protectedACMember?
var Module = (function (ns) {
function AbstractClass() {
this.protectedACMember = "abstract";
this.abstractPublicACMethod = function (input) {
this.methodToImplement();
}
}
ConcreteClass.prototype = new AbstractClass();
function ConcreteClass(){
var privateCCMember = "private CC";
var privateCCMethod = function(){
alert(this.protectedACMember); // cant find protectedACMember
}
this.methodToImplement = function(){
privateCCMethod();
console.log('Implemented method ');
}
}
ns.ConcreteClass = ConcreteClass;
return ns;
})(Module || {});
//somewhere later
var cc = new Module.ConcreteClass();
cc.abstractPublicACMethod();
are there any good patterns for simulating private, protected and public members? Static/non-static as well?
You should change that part of code like this:
var self = this;
var privateCCMethod = function(){
alert(self.protectedACMember); // this -> self
}
This way you get the reference in the closure.
The reason is, that "this" is a reserved word, and its value is set by the interpreter. Your privateCCMethod is an anonymous function, not the object property, so if you call it simply by privateCCMethod() syntax, this will be null.
If you'd like "this" to be bound to something specific you can always use .call syntax, like this:
privateCCMethod.call(this)
Another way to ensure that this means what you want is to use bind. Bind allows you to ensure a function is called with a specific value of this.
Most newer browsers support it (even IE9!) and there's a workaround for those that don't.
Bind - MDN Documentation
It fails to find protectedACMember because what the this keyword means changes when you enter the function privateCCMethod. A common practice is to store the outer this for use inside the functions:
function ConcreteClass(){
var privateCCMember = "private CC";
// store the outer this
var that = this;
var privateCCMethod = function(){
alert(that.protectedACMember);
}
...
The rest of your questions are fairly loaded and should probably be posted as a separate question.
I feel like what I have is correct code, but obviously I am missing something here.
What I am trying to do is create an event method in the prototype object of my constructor. Here is what I have so far:
function Controls(but) {
this.but = document.getElementById(but);
this.but.onclick = function() {
displayMessageTwo();
}
}
Controls.prototype.displayMessageTwo = function() {
alert("HELLO");
}
var Main = new Controls('testingTwo');
My logic here is that I am creating a constructor from which to build controls for something (let's say a slideshow).. this.but equals the html element of a link called whatever is passed as an argument to the constructor.
In my prototype object, I define my method and then create my object. However, this is not working as I had expected.
What am I doing wrong here?
I suspect that when the event handler fires, the context of the invocation is not the instance on which you registered the callback.
Try something like the following
function Controls(but) {
var that = this;
this.but = document.getElementById(but);
this.but.onclick = function() {
that.displayMessageTwo(); // that is closed-in
}
}
What am I doing wrong here?
You are calling displayMessageTwo(); as if it was a global function. It is not, it is a inherited property on your instance. Usually you would refer to the instance with the this keyword, but inside the event handler you can't. Create a variable referencing the object, and call that one's method like so:
function Controls(but) {
this.but = document.getElementById(but);
var that = this;
this.but.onclick = function() {
that.displayMessageTwo();
}
}
As your displayMessageTwo method does not care about its context (does not reference other properties via this), you even might assign it directly:
this.but.onclick = this.displayMessageTwo;
But I'd recommend to avoid that, methods should always be executed with correct thisValue. You also might use bind:
this.but.onclick = this.displayMessageTwo.bind(this);
but it needs additional code for older, non-supporting browsers.
I would think:
function Controls(but) {
this.but = document.getElementById(but);
this.but.onclick = this.displayMessageTwo;
}
Controls.prototype.displayMessageTwo = function() {
alert("HELLO");
}
var Main = new Controls('testingTwo');
is clearer (assigning the function assigned to prototype.displayMessageTwo). If this doesn't work it may be because
this.but.onclick = this.displayMessageTwo;
is evaluated before:
Controls.prototype.displayMessageTwo = function() {
making it null...