How do I "get" a member variable in JavaScript? - javascript

function User() {
this.firstname = null;
get getFirst() {
return this.firstname;
}
}
JavaScript console gives me an error saying "Unexpected Identifier" on line 12
var Jake = new User();
Jake.firstname = "Jake";
document.write(Jake.getFirst);

That's just not the syntax you use to define a getter. You'd use it in an object literal, like this:
var foo = {
get bar() {
return 42;
}
};
foo.bar; // 42
...but that's not where your get is.
To define it where your get is, you'd use defineProperty:
function User() {
this.firstname = null;
Object.defineProperty(this, "first", {
get: function() {
return this.firstname;
}
});
}
Note I called it first, not getFirst, because it's an accessor function, which looks like a direct property access, and so is traditionally not given a name in a verb form:
var u = new User();
u.firstname = "Paul";
u.first; // "Paul"
If you wanted to create a function called getFirst, just get rid of the get keyword:
this.getFirst = function() {
return firstname;
};
// ...
var u = new User();
u.firstname = "Paul";
u.getFirst(); // "Paul"

I believe the issue is that you are using get with a function rather than the object literal as outlined in the documentation.
var User = {
firstName: 'Darren',
get getFirst() { return this.firstName; }
}
alert(User.getFirst);
https://jsfiddle.net/ecao51n0/

get is intended to be called within an object, not a function constructor. If you want to declare getFirst as a function on User, then here's one way you could do it:
function User() {
this.firstname = null;
this.getFirst = function() {
return this.firstname;
}
}
Then you would also need to call getFirst as a function:
var Jake = new User();
Jake.firstname = "Jake";
document.write(Jake.getFirst());

Related

JavaScript Self Invoking function properties

Trying to understand JS better, have a couple of clarifications. Lets suppose we have the following method
var customer = function(){
var name = "Contoso";
return {
getName : function(){
return this.name;
},
setName : function(newName){
this.name = newName;
}
}
}();
why is name not visible outside ?, when we log (customer.name) its undefined, however if we remove the self initializing parenthesis on function and change the variable declaration to (this.name) & again when we log the same we are able to see the value. what am i missing in here.
You need to take in consideration that JavaScript doesn't really have native classes. With this said, the way you can create constructors in order to "mimic" a class and be able to use this you need to create something like so:
function fnc (string) {
this.string = string;
}
fnc.prototype.getString = function() {
return this.string;
}
var x = new fnc('bar');
console.log(x.getString()); //bar
This is called the Constructor Pattern.
What you're trying to do is use something called the Module Pattern which works something like so:
var fn = (function() {
var string = 'foo';
return {
getString() {
return string;
}
}
})();
console.log(fn.getString()); //foo
Here is a working example: https://repl.it/FCn7
Also, a good read: https://addyosmani.com/resources/essentialjsdesignpatterns/book/
Edit
Example using getString and setString with the Module Pattern
var fn = (function() {
var string = 'foo';
return {
getString() {
return string;
},
setString(str){
string = str;
}
}
})();
fn.setString('xyz');
console.log(fn.getString()); // xyz
var is creating variable inside function scope which is not available outside as function property. If you want to access properties like customer.name you need to initialize it as this.name as you noticed.
var in this example is like creating private variable which can be modified by functions, but not directly.
SO this will work:
var customer = function(){
var name = "Contoso";
return {
getName : function(){
return name;
},
setName : function(newName){
name = newName;
}
}
}();

Creating behaviour that is both like a JavaScript object literal as a function

I'd like to be able to do the following:
person('male');
person.age(34);
As you can see, I want the person object to be both a function as an object. What I mean is that doing so:
function person(gender){
this.gender = gender || 'unknown';
}
excludes me from doing so:
person.gender; // undefined
unless I create a new object from the person function, like so:
var me = new person();
me.gender; // 'unknown'
which I do not want, as I still want to be able to set other properties, like so:
person.age = 34;
Is this even possible? Of am I trying to accomplish the impossible?
To clarify: I don't want to need to create instances. The key is that I just want to be able to both call the function person as call a function.property().
EDIT: Perhaps I've confused many (including myself) by using a wrong example. A simpler question would be: How would I be able to call a function and a 'property' of that function, like so:
car();
car.start();
both at the same time without the need to create an instance of car?
We might be able to give a better answer if you would explain the motivation behind what you want to do. However, yes, what you describe is possible. In JavaScript, functions are just another type of object. That means that you could define a function, then set properties on it like so:
var person = function () {
return "Hi, I am a person!";
};
person.species = "human";
person.foo = 42;
console.log( person() ); // prints: Hi, I am a person!
console.log( person.species ): // prints: human
console.log( person.foo ); // prints: 42
Or working from your second example:
var car = function () {
return {
model: "Focus",
make: "Ford",
year: 2010
};
};
car.start = function () {
return "Vroom!";
};
console.log ( car.make ); // prints: Ford
console.log ( car.start() ); // prints Vroom!
By the way, this is not the same as a function that returns an object. That might look like this:
var person = function () {
return {
species: "human",
name: "Bob",
age: 27
};
};
var bob = person();
bob.occupation = "cubicle drone";
console.log( bob.name ); // prints: Bob
console.log( bob.occupation ); // prints: cubicle drone
console.log( person.occupation ); // prints: undefined
console.log( bob == person ); // prints: false
Variables bob and person both hold objects, but not the same object, not even the same type of object.
Instead of using this inside your function, which refers to the Object instance created when running this function as a constructor by invoking it with the new operator you can use arguments.callee to refer to the function itself
function person(gender){
arguments.callee.gender = gender || 'unknown';
}
If you want to ensure that a function is always used as a constructor even if invoked without the new operator, you can do it by implicitly invoking it.
function person(gender){
if(!(this instanceof person)){ return new person(gender); }
this.gender = gender || 'unknown';
}
In all other regards functions can do anything regular objects can, that's why they are often described as "first class objects".
You can simply assign them properties like objects, or methods like
function car(){
}
car.start = function(){
}
You can also let them inherit methods from a function using the __proto__ property.
function bird(){}
function platypus(){}
bird.layEggs = function(){};
platypus.__proto__ = bird;
platypus.layEggs() // now you know
a small example using the instanceof way that #Winchestro is using
on jsfiddle:http://jsfiddle.net/47EEr/
'use strict';
function person(gender, age, name) {
if (!(this instanceof person)) {
return new person(gender, age, name);
}
var props = { gender: '', age: 0, name: '' }, fnCreateProp = function(prop, value) {
Object.defineProperty(this, prop, {
get: function() {
return props[prop];
},
set: function(val) {
console.log('setting prop ' + prop + ' to ' + val);
props[prop] = val;
}
});
}.bind(this);
for (var prop in props) {
if (!props.hasOwnProperty(prop)) {
continue;
}
fnCreateProp(prop, props[prop]);
}
this.gender = gender;
this.age = age;
this.name = name;
this.toString = function(element) {
var str = '[Person=(';
for (var prop in props) {
if (!props.hasOwnProperty(prop)) {
continue;
}
if (str.indexOf('(') !== str.length-1) {
str += ',';
}
str += prop +': ' + props[prop];
}
str += ')]';
if (typeof element !== 'undefined') {
var el = document.getElementById(element);
if (el) {
el.innerHTML = str;
}
}
return str;
};
this.birthday = function() {
this.age++;
};
}
var p1 = person('male', 33, 'male 1');
var p2 = new person();
p2.age = 32; p2.gender = 'female'; p2.name = 'female 1';
p1.toString('person1');
p2.toString('person2');
p2.birthday();
p2.toString('person2birthday');
You can also do:
function person(gender){
return {
gender: gender || 'unknown'
};
}
var p = person('male');
p.age = 34;
p.name = 'John';
etc...
No "new" is used and you can still re-use the person function.
Your edit:
EDIT: Perhaps I've confused many (including myself) by using a wrong example. A simpler question would be: How would I be able to
call a function and a 'property' of that function, like so:
car();
car.start();
both at the same time without the need to create an instance of car?
Is this what you are looking for?
function car() {
console.log("car called");
car.start = function() {
console.log("car.start called");
}
}
car();
car.start();
/**** output:****
car called
car.start called
*/

JavaScript Function within Function

I was wondering if it is possible to do the following:
worker.name("John").salary(100)
Basically, this changes the worker's(John's) salary to 100.
Is there a way to define a function in a function?
Can you tell me the method and explain it?
This is often times called chaining. Essentially, each method returns the parent object:
var worker = {
name: function ( name ) {
this._name = name;
return this;
},
salary: function ( salary ) {
this._salary = salary;
return this;
}
};
worker.name("Jonathan").salary("$1");
alert( worker._name );
alert( worker._salary );
You'll note that each method returns the object. This is made very clear in the following screenshot. If we console output the results of calling the name method, we see that the entire worker object is returned:
Create a constructor function like:
var Worker = function(){
};
Worker.prototype.name = function (name){
this.name = name;
return this;
};
Worker.prototype.salary = function (salary){
this.salary = salary;
return this;
}
Now above constructor function can be used as:
var worker = new Worker();
worker.name("John Doe").salary(100);
This is possible:
var worker = {
nameVar: null,
salaryVar: null,
name: function(name) {
this.nameVar = name;
return this;
},
salary: function(salary) {
this.salaryVar = salary;
return this;
}
}
Each method modifies the object, and returns this, which is the object. Then you can call another method, like in your example, without writing the object name explicitly.
Alternatively, you can implement a .clone method, and instead of this, return the clone with a modified property. This would be somewhat similar to the way jQuery works.

Is it possible to append functions to a JS class that have access to the class's private variables?

I have an existing class I need to convert so I can append functions like my_class.prototype.my_funcs.afucntion = function(){ alert(private_var);} after the main object definition. What's the best/easiest method for converting an existing class to use this method? Currently I have a JavaScript object constructed like this:
var my_class = function (){
var private_var = '';
var private_int = 0
var private_var2 = '';
[...]
var private_func1 = function(id) {
return document.getElementById(id);
};
var private_func2 = function(id) {
alert(id);
};
return{
public_func1: function(){
},
my_funcs: {
do_this: function{
},
do_that: function(){
}
}
}
}();
Unfortunately, currently, I need to dynamically add functions and methods to this object with PHP based on user selected settings, there could be no functions added or 50. This is making adding features very complicated because to add a my_class.my_funcs.afunction(); function, I have to add a PHP call inside the JS file so it can access the private variables, and it just makes everything so messy.
I want to be able to use the prototype method so I can clean out all of the PHP calls inside the main JS file.
Try declaring your "Class" like this:
var MyClass = function () {
// Private variables and functions
var privateVar = '',
privateNum = 0,
privateVar2 = '',
privateFn = function (arg) {
return arg + privateNum;
};
// Public variables and functions
this.publicVar = '';
this.publicNum = 0;
this.publicVar2 = '';
this.publicFn = function () {
return 'foo';
};
this.publicObject = {
'property': 'value',
'fn': function () {
return 'bar';
}
};
};
You can augment this object by adding properties to its prototype (but they won't be accessible unless you create an instance of this class)
MyClass.prototype.aFunction = function (arg1, arg2) {
return arg1 + arg2 + this.publicNum;
// Has access to public members of the current instance
};
Helpful?
Edit: Make sure you create an instance of MyClass or nothing will work properly.
// Correct
var instance = new MyClass();
instance.publicFn(); //-> 'foo'
// Incorrect
MyClass.publicFn(); //-> TypeError
Okay, so the way you're constructing a class is different than what I usually do, but I was able to get the below working:
var my_class = function() {
var fn = function() {
this.do_this = function() { alert("do this"); }
this.do_that = function() { alert("do that"); }
}
return {
public_func1: function() { alert("public func1"); },
fn: fn,
my_funcs: new fn()
}
}
var instance = new my_class();
instance.fn.prototype.do_something_else = function() {
alert("doing something else");
}
instance.my_funcs.do_something_else();
As to what's happening [Edited]:
I changed your my_funcs object to a private method 'fn'
I passed a reference to it to a similar name 'fn' in the return object instance so that you can prototype it.
I made my_funcs an instance of the private member fn so that it will be able to execute all of the fn methods
Hope it helps, - Kevin
Maybe I'm missing what it is you're trying to do, but can't you just assign the prototype to the instance once you create it? So, first create your prototype object:
proto = function(){
var proto_func = function() {
return 'new proto func';
};
return {proto_func: proto_func};
}();
Then use it:
instance = new my_class();
instance.prototype = proto;
alert(instance.prototype.proto_func());

access parent object in javascript

var user = {
Name: "Some user",
Methods: {
ShowGreetings: function() {
// at this point i want to access variable "Name",
//i dont want to use user.Name
// **please suggest me how??**
},
GetUserName: function() { }
}
}
You can't.
There is no upwards relationship in JavaScript.
Take for example:
var foo = {
bar: [1,2,3]
}
var baz = {};
baz.bar = foo.bar;
The single array object now has two "parents".
What you could do is something like:
var User = function User(name) {
this.name = name;
};
User.prototype = {};
User.prototype.ShowGreetings = function () {
alert(this.name);
};
var user = new User('For Example');
user.ShowGreetings();
var user = {
Name: "Some user",
Methods: {
ShowGreetings: function() {
alert(this.Parent.Name); // "this" is the Methods object
},
GetUserName: function() { }
},
Init: function() {
this.Methods.Parent = this; // it allows the Methods object to know who its Parent is
delete this.Init; // if you don't need the Init method anymore after the you instanced the object you can remove it
return this; // it gives back the object itself to instance it
}
}.Init();
Crockford:
"A privileged method is able to access the private variables and
methods, and is itself accessible to the public methods and the
outside"
For example:
function user(name) {
var username = name;
this.showGreetings = function()
{
alert(username);
}
}
You can try another approach using a closure:
function userFn(name){
return {
Methods: {
ShowGreetings: function() {
alert(name);
}
}
}
}
var user = new userFn('some user');
user.Methods.ShowGreetings();
Old question but why can't you just do something like this :
var user = {
Name: "Some user",
Methods: {
ShowGreetings: function() {
// at this point i want to access variable "Name",
//i dont want to use user.Name
// **please suggest me how??**
var thisName = user.Name; //<<<<<<<<<
},
GetUserName: function() { }
}
}
Because you will only call user.Methods.ShowGreetings() after the user has been instantiated. So you will know about the variable 'user' when you want to use its name ?
As others have said, with a plain object it is not possible to lookup a parent from a nested child.
However, it is possible if you employ recursive ES6 Proxies as helpers.
I've written a library called ObservableSlim that, among other things, allows you to traverse up from a child object to the parent.
Here's a simple example (jsFiddle demo):
var test = {"hello":{"foo":{"bar":"world"}}};
var proxy = ObservableSlim.create(test, true, function() { return false });
function traverseUp(childObj) {
console.log(JSON.stringify(childObj.__getParent())); // returns test.hello: {"foo":{"bar":"world"}}
console.log(childObj.__getParent(2)); // attempts to traverse up two levels, returns undefined because test.hello does not have a parent object
};
traverseUp(proxy.hello.foo);
Very late to the party, but this works
var user = {
Name: "Some user",
Methods() {
return {
that: this,
ShowGreetings: function() {
console.log(this.that.Name)
},
GetUserName: function() { }
}
}
}
user.Methods().ShowGreetings() // Some user
David Dorward's right here. The easiest solution, tho, would be to access user.Name, since user is effectively a singleton.
ES6 Classes
One simple solution would be to create a Class with methods!
class User {
// Assign properties when an instance
// is created using the `new` keyword
constructor(name) {
this.name = name;
}
// Methods:
showGreetings() {
console.log(`Hello, ${this.name}!`);
}
getUserName() {
return this.name;
}
// Or rather, use Getters:
get username() {
return this.name;
}
}
// Create a new user:
const user = new User("Praveen");
// Use methods:
user.showGreetings(); // "Hello, Praveen!"
console.log(user.getUserName()); // "Praveen"
console.log(user.username); // "Praveen"
Why the above suggestion? Mostly because:
you cannot reference a parent Object from a child Object directly
const User = {
name: "Some user", // hardcoded stuff? Is this an intentional Singleton?
methods: { // <<< Child Object of User
sayName() {
// Sadly, `this` refers to `methods`, not to `user`:
console.log(this); // methods{}
console.log(User.name); // "Some user" // Get Singleton's name
// ... but that's not what you want.
}
}
};
User.methods.sayName();
// ^^^^^^^ Why would you want this `methods` anyways?!
and it makes no sense to hardcode Strings (like "Some user") inside an Object Singleton — which could actually be a reusable function Object.
If you want to associate a child Node to a parent Node — read this answer (Get value of parent Object).
How about this way?
user.Methods.ShowGreetings.call(user, args);
So you can access user.Name in ShowGreetings
var user = {
Name: "Some user",
Methods: {
ShowGreetings: function(arg) {
console.log(arg, this.Name);
},
GetUserName: function() { }
},
Init: function() {
this.Methods.ShowGreetings.call(this, 1);
}
};
user.Init(); // => 1 "Some user"
As a variant:
var user = (obj => {
Object.keys(obj.Methods).map(option => {
const currOpt = obj.Methods[option];
if (currOpt instanceof Function) {
obj.Methods[option] = currOpt.bind(obj);
};
});
return obj;
})({
Name: "Some user",
Methods: {
Greeting: function () { return this.Name },
GetUserName: function() { console.log(this) }
},
});
But I don't know why somebody can use this strange approach
I know I'm very late.
I wrote this simple method. Let's say you have:
{
subObj: {
x:'hello_world';
}
}
Then, if you want a reference to the bigger object from subObj, you can convert it to a function, and utilize this.
var tmpVal=reference_to_subObj; //keep value of subObj safe
reference_to_subObj=function(){return this;}//this returns the scope, here the parent
var parent=reference_to_subObj(); //call the function
reference_to_subObj=tmpVal; delete tmpVal; //set things back to normal
//Now you have variable 'parent'.
I used a Function() constructor because it let me create the function as a string, so I could pass a string as code.
function findParent(stringReference) {
Function(/*same as above, except filled in all reference_to_subObj with stringReference.*/
//stringReference is a stringified version of dot or bracket notation.
So I could call findParent('obj.subObj').
// Make user global
window.user = {
name: "Some user",
methods: {
showGreetings: function () {
window.alert("Hello " + this.getUserName());
},
getUserName: function () {
return this.getParent().name;
}
}
};
// Add some JavaScript magic
(function () {
var makeClass = function (className) {
createClass.call(this, className);
for (key in this[className]) {
if (typeof this[className][key] === "object") {
makeClass.call(this[className], key);
}
}
}
var createClass = function (className) {
// private
var _parent = this;
var _namespace = className;
// public
this[className] = this[className] || {};
this[className].getType = function () {
var o = this,
ret = "";
while (typeof o.getParent === "function") {
ret = o.getNamespace() + (ret.length === 0 ? "" : ".") + ret;
o = o.getParent();
}
return ret;
};
this[className].getParent = function () {
return _parent;
};
this[className].getNamespace = function () {
return _namespace;
}
};
makeClass.call(window, "user");
})();
user.methods.showGreetings();
I ran across this old post trying to remember how to solve the problem. Here is the solution I used. This is derived from Pro JavaScript Design Patterns by Harmes and Diaz (Apress 2008) on page 8. You need to declare a function and then create a new instance of it as shown below. Notice the Store method can access "this".
function Test() {
this.x = 1;
}
Test.prototype = {
Store: function (y) { this.x = y; },
}
var t1 = new Test();
var t2 = new Test();
t1.Store(3);
t2.Store(5);
console.log(t1);
console.log(t2);
Like #Quentin said, there is no upwards relationship in JS. However try this workaround;
foo = { bar: {parent: foo} };
console.log(foo);
console.log(foo.bar.parent);
which is also similar to;
function Foo(){
this.bar = {parent: this}
}
foo = new Foo();
console.log(foo);
console.log(foo.bar.parent);

Categories

Resources