var myProp = function() {
this.name = name;
this.gender = gender;
this.age = age;
}
So I have JS class with a bunch of properties. That look like that above.
$('#nav li').on('click', function() {
var selected_li = $(this);
function getProp() {
myProp = function() {
return this.name + 'John' + this.gender + 'Male' + this.age + 'Nine';
}
}
});
console.log(myProp);
onClick of my element, i'm trying to update the properties within myProp so if I do console.log() i'll get name = 'John', gender = 'male' and so on.
Is it something to do with the scope why I cannot update my properties of myProp?
Whenever I console log myProp I just get back myProp, exactly how it is without any properties being updated?
Still learning, apologies if this seems stupid.
Thanks.
In your first code block, you appear to have some global JS that sets a global variable (myProp) to a function.
In your second code block, you have an event handler which defines a locally scoped function declaration called myProp.
That function masks the global one for the lifetime of the call to the event handler.
You never call the locally scoped myProp, but if you did, it would immediately overwrite itself with a different function (defined with a function expression).
At no point do you ever touch the global myProp, and you never do anything with the local one.
It looks like you just want to have a global object with some properties in it. If you wanted to change the values of those properties you would do something like this:
var myProp = {
name: name,
gender: gender,
age: age,
}
$('#nav li').on('click', function() {
myProp.name = "John";
myProp.gender = "Male";
myProp.age = "Nine";
});
Assuming I've understood your question correctly, you can modify the property values of an instance of myProp:
// Create an instance of myProp
var myPropInstance = new myProp('name', 'gender', 'age');
$('#nav li').on('click', function() {
var selected_li = $(this);
// Update the property values of an instance of myProp
myPropInstance.name = 'new name';
});
Notice that I'm passing values into the myProp constructor... you'll probably want to update that constructor to set instance properties based on those:
var myProp = function(name, gender, age) {
this.name = name;
this.gender = gender;
this.age = age;
}
This is your constructor. It's the blueprints for making an object.
function Person(name, gender, age) {
this.name = name;
this.gender = gender;
this.age = age;
}
Creating a person
var John = new Person("John", "Male", "Nine");
Changing Johns gender:
John.gender = "Female"
create getter and setter like this
var myProp = function() {
this.name = "k"
var self = this
this.setName =function(name){
self.name = name
}
this.getName =function(){
return self.name
}
}
then use new to get its method
var myObject = new myProp();
myObject.getName()
myObject.setName("new name")
myObject.getName()
Related
I kind of know that we cannot observe properties of an object by simply observing an object. But I want to know if my understanding is correct.
Can we do something like this ? http://jsfiddle.net/Z3gNC/
function Person(name, age) {
this.name = name;
this.age = age;
}
$(function () {
var vm = (function () {
var person = ko.observable(new Person("ABC", 23));
return {
person: person
};
})();
ko.applyBindings(vm);
});
It is not working so we can't I guess. I also don't understand where this character 'c' comes from.
You're not far off, you just need to unwrap your person observable when referencing it in your markup:
Updated JSFiddle
<input data-bind="value:person().name" />
<input data-bind="value:person().age" />
Edit from comment
Update JSFiddle
You can make the properties of Person observable so that they track changes like so:
function Person(name, age) {
this.name = ko.observable(name);
this.age = ko.observable(age);
}
I just updated your fiddle to be the more-usual KO pattern:
http://jsfiddle.net/Z3gNC/1/
function Person(name, age) {
this.name = ko.observable(name);
this.age = ko.observable(age);
}
$(function () {
var vm = (function () {
var person = new Person("ABC", 23);
return {
person: person
};
})();
ko.applyBindings(vm);
});
The reason you see 'c' in your original fiddle is because vm.person is a ko.observable function, which when minimised looks like:
function c(){if(0<arguments.length)return c.Ka(d,arguments[0])&&(c.P(),d=arguments[0],c.O()),this;a.k.zb(c);return d}
Every function has a name property:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
so in this case vm.person.name is the name of the function vm.person which when minified is 'c' !
Edit: if you use a single observable Person, KO won't know that the inner property changes, unless you tell it with a valueHasMutated call. This next demo uses your VM structure and binds the changes in the textbox to the span, via a change event and a valueHasMutated call. So it works, but the 'pure' KO approach above is perhaps preferable for simplicity.
http://jsfiddle.net/Z3gNC/6/
function Person(name, age) {
this.name = name;
this.age = age;
}
$(function () {
var vm = (function () {
var person = ko.observable(new Person("ABC", 23));
var mutate = function(data, event) {
data.person.valueHasMutated();
}
return {
person: person,
mutate: mutate
};
})();
ko.applyBindings(vm);
});
... which needs this HTML:
<input data-bind="value:person().name, event: {change: mutate}" />
Ok so the following function acts as a constructor to create an Employee object(no problem with that). But when I use this function to create 3 new employees I am messing up somewhere.
I know I'm supposed to set the properties and print the employee's name and phone number, but I am missing something or something is in the wrong place.
Thanks in advance for your help.
function Employe() {
var = name;
var = phone;
this.getName = function () {
return this.name;
}
this.setName = function (name, phone) {
this.name = name;
this.phone = phone;
};
}
var emp1 = newEmployee;
this.Name = 'jo';
this.Phone = ' 555-5551'
document.write(Employee.name Employee.phone);
var emp2 = newEmployee;
this.Name = 'jim';
this.Phone = '555-5552';
document.write(Employee.name Employee.phone);
var emp3 = newEmployee;
this.Name = 'jon';
this.Phone = '555-5553';
document.write(Employee.name Employee.phone);
In the following:
> var emp1 = newEmployee;
The variable on the left will be assigned the result of evaluating the expression on the right. There is no identifier newEmployee, so you will get an error. What you probably meant to write is:
var emp1 = new Employee();
That will call the constructor, which will return a new instance, a reference to which will be assigned to emp1.
Then you have:
> this.Name = 'jo';
The value of this is set when entering an execution context. For global code, it always references the global object (which is equivalent to window in a browser). So the above line creates a Name property of the global object and assigns the value 'jo';
What you wanted is probably:
emp1.setName('jo','555-5551');
The name of that method seems inappropriate given that it sets both the name and phone number.
> document.write(Employee.name Employee.phone);
Since you added the properties to the instance (emp1), likely that's the properties you want to read:
document.write(emp1.name + ' ' + emp1.phone);
or to use the getName method:
document.write(emp1.getName() + ' ' + emp1.phone);
and so on.
There's a lot wrong with your code example. The constructor is misspelled. The employee instances should be created like:
var emp1 = new Employee();
The instance properties should be set like:
emp1.setName('John');
You've also combined two setters into one, which is confusing.
To access the instance properties, you should use:
emp1.getName();
Not:
Employee.Name
Yes you have a lot of errors I think this is basically what you want to achieve.
function Employee(){
this.name;
this.phone;
this.getName = function(){
return this.name;
};
this.setName = function(name, phone){
this.name = name;
this.phone = phone;
};
}
function employ(){
var emp1 = new Employee();
emp1.name = 'jo';
emp1.phone = ' 555-5551' ;
alert(emp1.getName());
}
http://jsfiddle.net/umNTs/
I would like to display name, age, job in an alert message box, how do I do that?
function createPerson(name, age, job) {
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () {
alert(this.name);
};
return o;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
jsFiddle Demo
"I would like to display name, age, job in an alert message box, how do I do that?"
Access the properties on the object using .name, .age, and .job like this:
alert(person1.name+" "+person1.age+" "+person1.job); from the outside. If you would like to have the object be able to use this alert then you can attach it like this:
o.alertInformation = function(){ alert(this.name+" "+this.age+" "+this.job); };
function createPerson(name, age, job){
var o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
};
o.alertInformation = function(){ alert(this.name+" "+this.age+" "+this.job); };
return o;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
//example of accessing the object properties with dot notation
//alternatively, you could use person1["name"] to access them
alert(person1.name+" "+person1.age+" "+person1.job);
//or if you want to use an internal method on person
person1.alertInformation();
jsFiddle Demo
Blurb on "factory" pattern:
Usually an approach is used where the new keyword is called on a function. When new is used on a function, it creates a scope in the function where this refers to the function object. Using this.name inside of a function called with new will attach name to the object. When you use new, it implicitly assigns the function object to the variable, in the below example, p is used.
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype.sayName = function(){
alert(this.name);
};
Person.prototype.alertInformation = function(){
alert(this.name+" "+this.age+" "+this.job);
};
var p = new Person('Nicholas', 29, 'Software Engineer');
p.sayName();
p.alertInformation();
jsFiddle Demo
For this to be an actual factory, remember that it has to be involved with the actual creation of the objects, not just implicitly returning them. To do this, we would need a PersonFactory (sounds strange :P).
function personFactory(){
var People = [];
var autoIncId = 0;
return {
Create: function(name,age,job){
var p = new Person(autoIncId++,name,age,job);
People.push(p);
return p;
},
GetPersonById: function(id){
return People[id];
}
};
}
which would then be used:
var pf = personFactory();
var p = pf.Create('Nicholas', 29, 'Software Engineer');
p.sayName();
p.alertInformation();
function createPerson(name, age, job){
this.name=name;
this.age=age;
this.job=job;
if(createPerson._intialized=="undefined"){
createPerson.prototype.sayPersonInfo=function(){
alert('i am '+this.name+' , '+this.age+'years old and my job is '+this.job);
}
createPerson._initialized=true;
}
var person1 = createPerson('Nicholas', 29, 'Software Engineer');
var person2 = createPerson('Greg', 27, 'Doctor');
person1.sayPersonInfo();
this method is called ' dynamic prototype ' and is the best way in know .
i hope this can help ...
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.
I have an object written like this:
Object1.prototype = {
isInit: false,
Get : function (){}
}
Now I'd like to add a constructor which takes one parameter. How can I do it?
Class declaration
var User = function(name, age) { // constructor
}
User.prototype = {}
Instance variables (members)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {}
Static variables
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
staticVar: 15,
anotherStaticVar: 'text'
}
Here I defined two static variables. Each User instance has access to these two variables. Note, that we can initialize it with value;
Instance functions (methods)
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.prototype = {
getName: function() {
return this.name;
},
setName: function(name) {
this.name = name;
}
}
Usage example:
var user = new User('Mike', 29);
user.setName('John');
alert(user.getName()); //should be 'John'
Static functions
var User = function(name, age) {
this.name = name;
this.age = age;
}
User.create = function(name, age) {
return new User(name, age);
}
User.prototype = {}
Assuming that by "ctor" you mean "constructor", in JavaScript that's just a function. In this case your constructor would need to be "Object1" itself - in other words, what you've got there makes sense if you have already defined "Object1" to be a function.
Thus,
function Object1(param) {
// constructor code
}
would be the constructor for your type.
Now there are some JavaScript libraries that provide a utility layer for defining classes. With those, you generally pass some sort of object (like you've got) that includes an "init" function. The libraries provide APIs for creating "classes" and for extending one class from another.
Javascript has prototype based object model. Check this mozilla wiki page and suddenly you'll feel much better in js land.
We can define a constructor in javaScript is same as we fine function, so constructor is just a function.
//function declaration
function func(){}
In case of Contructor We use initial letter in caps in construct like
//constructor
function Func(){}
now do whatever you want to with your constructor
var constructor1 = new Func();
class CLASS_NAME
{
private:
int variable;
public:
CLASS_NAME() //constructor
{
variable = 0;
}
};