How to access properties in oop javascript via object, I am getting following error : "Uncaught TypeError: x.firstname is not a function
at newindex.html:19"
How do I access firstname using x object
function person() {
this.firstName = "hello";
}
var x = new person();
console.log(x.firstname());// how to get firstname from x ??
firstName should be with captital letter N and accessed without parenthesis.
Change this line:
console.log(x.firstname());// how to get firstname from x ??
To this line:
console.log(x.firstName);// how to get firstname from x ??
Firstname is a property, not a function so including parentheses at the end is what is creating your error. You are also not case matching your variables firstname != firstName. Here is an example of accessing a property and also a function.
function Person() {
this.firstName = "hello";
this.firstNameFunc = function() { return 'function exec' };
}
let person = new Person();
console.log(person.firstName);
console.log(person.firstNameFunc());
firstName is a property , not a function. You should do,
console.log(x.firstName);
DEMO
function person() {
this.firstName = "hello";
}
var x = new person();
console.log(x.firstName);
Related
I'm new to JavaScript and I'm having a little trouble with execution context; the value of this.
Consider the following:
const name = "Mary";
const proto = {
hello: () => `Hello, my name is ${ this.name }.`
};
const greeter = name => Object.assign(Object.create(proto), { name });
const joe = greeter("Joe");
console.log(joe.hello());
I expected the log would be: Hello, my name is Joe. But this was instead the global object. It returned Hello, my name is Mary.
On the other hand:
const name = "Mary";
const proto = {
hello() { return `Hello, my name is ${ this.name }.` }
};
const greeter = name => Object.assign(Object.create(proto), { name });
const joe = greeter("Joe");
console.log(joe.hello());
This time the expected string was returned; the only difference is the "method definition" inside the proto object.
So my question is what is the second syntax even called?
It is not a function declaration nor a function expression, so what is it? Either way I expected the property accessor invocation from the 'greeter' object, 'joe' to associate this to the object itself.
And when should I use a function expression and when should I use this alternative form of declaring an object's method?
I hope this makes sense and thank you in advance for you attention.
I have been learning JS on my own and completed an 8 hour course on the basics. Now I am following another course where the lecturer, as it seems to me, is creating a function using dot notation. I am not sure if this is what is happening and I am having a hard time understanding exactly what it is doing.
function Person(fName, lName) {
this.firstName = fName
this.lastName = lName
}
const person1 = new Person("Bruce", "Wayne")
const person2 = new Person("Bat", "Man")
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
console.log(person1.getFullName())
The part I am confused about is:
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
I see in the Person() function we are creating an object called person1 using "this" and a key to pass in parameters as values for those keys. However it looks to me like there is a function being assigned to the person1 object and what I am assuming is the name of the function, looks like a method on the person1 object using dot notation. Can anyone explain how this works?
The line
person1.getFullName = ...
is a normal assignment statement. It assigns the value on the right hand side to the property getFullName of the object in person1. If the property doesn't exist yet it will be created.
Functions are values (objects) like any other in JavaScript and thus they can be used everywhere were a value is expected.
So yes, person1.getFullName will contain a function and it can be called like any other function: person1.getFullName().
Objects have properties.
Properties have values.
Functions are a value.
If the value of a property is a function then we call that a method.
That's all there is to it.
function Person(fName, lName) {
this.firstName = fName
this.lastName = lName
}
const person1 = new Person("Bruce", "Wayne")
const person2 = new Person("Bat", "Man")
person1.getFullName = function () {
return this.firstName + ' ' + this.lastName
}
console.log(person1.getFullName())
Basically a new property called getFullName is created for the object person1. This new property is defined to return the first name and the lastname of the person1 object. So when you call console.log(person1.getFullName()) this will print the firstname and the lastname of the person1.
I am having some trouble understanding function scope in JavaScript:
function Person() {
var _firstName;
var _lastName;
}
personOne = new Person();
personOne._firstName = "Fred";
alert(personOne._firstName);
This outputs "Fred", but I thought the variables of the Person function would only be accessible inside the function. Why does it work?
In JavaScript, objects are dynamically-expandable.
For example:
var obj = {};
obj.firstName = "MatÃas"; // <-- This adds the property even if it doesn't exist
In the other hand, if you want to declare properties that should be part of the object in the constructor function you need to qualify them with this:
function Person() {
this._firstName = null;
this._lastName = null;
}
Extra info
If you want to avoid objects from being dynamically-expandable, you can use the ECMA-Script 5 Object.preventExtensions function:
var obj = {};
Object.preventExtensions(obj);
// This property won't be added!
obj.text = "hello world";
Because in the line:
personOne._firstName = "Fred";
You assigned a new property to the object with a value of "Fred". It has nothing to do with the (internally-scoped) variable you declared inside the function.
And in the following line, you're actually alerting the value of the newly-created property and not the variable.
See MDN
It works because you create the property _firstName for the object Person.
personOne._firstName = "Fred"; // here you create the property
In the example below I highlighted the fact that _firstName is innacesible.
function Person() {
var _firstName= "Fred";;
var _lastName;
}
personOne = new Person();
alert(personOne._firstName); // output: "undefined"
If you want to make them accesible you can make use of this to add a new property to the object.
function Person() {
var self = this;
self._firstName= "Fred";
var _lastName;
return self;
}
var personOne = new Person();
alert(personOne._firstName); // output: "Fred"
In this line:
personOne._firstName = "Fred";
you are actually creating the property _firstName of the object. it is not the same as the var you created in the constructor function. You can always add new properties to a JavaScript object. Each property of an object is accessible. There is no such thing as a private property.
Due to function scope you will not be able to change the variables inside Person() from outside if you do not make methods available in Person to set the values of those variables.
function Person(firstName, lastName) {
var _firstName = firstName, _lastName = lastname;
this.getFullName = function () {
return _firstName + " " + _lastName;
};
}
var someone = new Person("Some", "one");
someone._firstName = "something else"; // creates new property in the object someone
var fullName = someone.getFullName(); // still returns "some one"
You cannot reference _firstName inside the object declaration. If you want to access the object property you need to declare with this, otherwise the _firstName or _lastName are considered local variables.
So to access the _firstName or _lastName as object properties, you have to declare as in the following way:
function Person() {
this._firstName = "John";
this._lastName = "Doe";
}
You may access _firstName and _lastName after you instantiate the Person.
personOne = new Person();
personOne._firstName = "Fred";
This way you will override the properties already defined in the object constructor. In your case because _firstName is declared inside the Object definition the scope of that variable is bind locally to that object. But when you instantiate the object you assign a new property which extends the originally declared object.
The most widely accepted pattern is to bind the object properties on the object declaration, but declare the object methods on their prototype level.
Like so:
function Person() {
this._firstName;
//...
}
Person.prototype = function() {
getName : function() {
//...
},
setName : function(name) {
this._firstName = name;
}
}
JS objects objects are "expandable", you can add properties dinamically.
function Person() {
var _firstName;
var _lastName;
}
var personOne = new Person();
console.log(personOne); // Person {}
personOne._firstName = "Fred";
personOne._age = 20;
console.log(personOne); // Person {_firstName: "Fred", _age: 20}
You don't actually have access to the _firstName created inside the function scope, but rather you create a property with that name on your newly created object.
In order to expose a property, you attach it using this keyword (which is a reference to the newly created object).
function Person() {
console.log(this); // Person {}
this._firstName = "Sam";
console.log(this); // Person {_firstName: "Sam"}
}
I am practicing Javascript object function. Supposed I have firstName and lastName as two arguments of my function.I want to display like this {"firstName":"tim","lastName":doe} . Here is my code but it printed out undefined. Any idea? Thank you!
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction();
console.log(myFunction('tim', 'doe'));
Try this:
console.log(new myFunction('tim', 'doe'));
Or this:
console.log(obj);
You can try this
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);
You can see this documentation JavaScript Constructors
This kind of function called constructor, and you shouldn't call it directly. You have to use it with new.
console.log(new myFunction('tim', 'doe'));
This will print the result as you expect.
To distinguish the constructors from normal functions, it's better to name it begin with capital letter, like this:
function MyFunction(...) {...}
the undefined you receive is from the function not having a return value, see this post regarding that:Simple function returning 'undefined' value
to get the result you want...
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
}
var obj = new myFunction('tim', 'doe');
console.log(obj);
Let's explore what this line does: console.log(myFunction('tim', 'doe'));
This part: myFunction('tim', 'doe') executes myFunction as a function. Since myFunction does not have a return operator, it's return value is 'undefined' which is javascript's way of saying it doesn't exist. Thus, the word 'undefined' is printed on the console.
Additional tips:
Try adding this line: console.log(typeof myFunction);
This should print 'function'.
(May the 'typeof' operator become your best friend)
Try adding a return line as the last line of myFunctions such as:
return 'First name: ' + firstName + " Last name: " + lastName;
However, at this point the 'var obj = new myFunction();' line is unused.
Try adding another line:
console.log(typeof obj);
This should print 'object' which means that 'obj' is just that - an object.
Here is a complete example you can play with:
function myFunction(firstName, lastName) {
this.name1 = firstName;
this.name2 = lastName;
this.getNames = function() {
return 'First name: ' + firstName + " Last name: " + lastName;
}
console.log("This executes once upon instatiation (the line with var obj = new ...)");
return "Return value";
}
var obj = new myFunction('tim', 'doe');
console.log(typeof myFunction);
console.log(typeof obj);
console.log(obj.getNames());
Let me know if any of the above needs clarification. Good luck ...
BTW, this is what the output should look like on the console:
This executes once upon instatiation (the line with var obj = new ...)
script.js:14 function
script.js:15 object
script.js:16 First name: tim Last name: doe
I have the following javascript
function person() {
//private Variable
var fName = null;
var lName = null;
// assign value to private variable
fName = "Dave";
lName = "Smith";
};
person.prototype.fullName = function () {
return this.fName + " " + this.lName;
};
var myPerson = new person();
alert(myPerson.fullName());
I am trying to get an understanding of object orientated techniques in javascript. I have a simple person object and added a function to its prototype.
I was expecting the alert to have "Dave Smith", however I got "underfined underfined". why is that and how do I fix it?
Unfortunately you can't access a private variable. So either you change it to a public property or you add getter/setter methods.
function person() {
//private Variable
var fName = null;
var lName = null;
// assign value to private variable
fName = "Dave";
lName = "Smith";
this.setFName = function(value){ fName = value; };
this.getFName = function(){ return fName; }
};
see javascript - accessing private member variables from prototype-defined functions
But actually this looks like what you are looking for:
Javascript private member on prototype
from that SO post:
As JavaScript is lexically scoped, you can simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.
in your case:
var Person = (function() {
var store = {}, guid = 0;
function Person () {
this.__guid = ++guid;
store[guid] = {
fName: "Dave",
lName: "Smith"
};
}
Person.prototype.fullName = function() {
var privates = store[this.__guid];
return privates.fName + " " + privates.lName;
};
Person.prototype.destroy = function() {
delete store[this.__guid];
};
return Person;
})();
var myPerson = new Person();
alert(myPerson.fullName());
// in the end, destroy the instance to avoid a memory leak
myPerson.destroy();
Check out the live demo at http://jsfiddle.net/roberkules/xurHU/
When you call person as a constructor, a new object is created as if by new Object() and assigned to its this keyword. It is that object that will be returned by default from the constructor.
So if you want your instance to have properties, you need to add them to that object:
function Person() {
// assign to public properties
this.fName = "Dave";
this.lName = "Smith";
};
Incidentally, by convention functions that are intended to be called as constructors are given a name starting with a capital letter.
You're declaring those variables as local to the function, instead of making them part of the object. In order to put them in the instance, you've got to use 'this' in the constructor as well. For example:
function person() {
this.fName = 'Dave';
this.lName = 'Smith';
}
person.prototype.fullName = function () {
return this.fName + " " + this.lName;
};
var myPerson = new person();
alert(myPerson.fullName());
In the constructor you should assign your variables to this:
this.fName = null;
this.lName = null;
But then they are not private. JavaScript does not have private variables like a "classic" Object Oriented language. The only "private" variables are local variables. An alternative to the above is to assign getter/setter methods to this within the constructor.