What is the difference between this...
function Person(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
and this...
function Person(name) {
this.name = name;
this.age = age;
this.sex = sex;
}
and this...
function Person() {
this.name = name;
this.age = age;
this.sex = sex;
}
Thanks!
David, I have a piece of code for a game I am building that looks like this...
function Player(node){
this.node = node;
this.grace = false;
this.replay = 3;
this.shield = 3;
this.respawnTime = -1;
...
return true;
}
and it does not return a reference error. Its an object for a player in a javascript game I am building...
As Brett said, the second and third constructor function will assign any global variable to the properties of the new Person instance. However, you can still use any argument that might be passed to the constructor:
function Person()//no args
{
//depending on which value is available:
//prop = n-th argument OR global variable OR undefined
this.name = arguments[0] || window.name || undefined;
this.age = arguments[1] || window.age || undefined;
this.sex = arguments[2] || window.sex || undefined;
}
var parrot = new Person('polly',1,'M');
console.log(parrot.name);//polly
var noSex = new Person('Joe',99);//if no global sex is set:
console.log(noSex.sex);//undefined
var sex = 'F';
var jane = new Person('Jane',25);
console.log(jane.sex);//F
The first relies on local variables set through parameters to set its instance variables/properties, the third relies on globals to set its properties, and the second is a mix.
1st one is valid, you initite your local variables with the parameters sent in the constructor. the rest doesnt really make sense.
in the 2nd one you kind of mixing parameters with some other variables which you can access at that point, you initate only the name using a parameter.
and the 3rd one is based on accessable variables, but none of them is given as a parameter, i never saw something usefull using 2nd and 3rd options..
Related
I'm trying to learn JavaScript, but got stuck with a problem (more with misunderstanding "this" keyword) that doesn't give me move on.
I've watched a lot of content about it and barely understood it, but still have some troubles.
I have some code:
function Person (name, age) {
this.name = name;
this.age = age;
this.changeName = function (name) {
this.name = name;
}
}
What do we use "this" here for?
As I understood we use "this" to create variable inside function constructor and give it value of our "name" parameter that we could refer to it. Am I right?
Then I have this code:
var p1 = new Person ("John", 30);
p1.changeName ("Jane");
console.log(p1.name);
As I sorted out here, we call method that overwrites our variable that we created to refer to. But it doesn't change actual parameter. So if it's right why do we use it? Doesn't it matter to have actual "name" parameter changed?
The whole code is from teaching app!
So if it's right why do we use it? Doesn't it matter to have actual "name" parameter changed?
No, there's no need to do that in this example. changeName changes the property on the object that was created by new Person.
It's true that that example code is a bit odd, because it creates the changeName function in the constructor but doesn't do the kinds of things you'd normally do when you create the function in the constructor. I'd expect that code to either be this, which puts the changeName on the prototype:
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.changeName = function(name) {
this.name = name;
};
(or the class equivalent) or this:
function Person(name, age) {
this.getName = function() {
return name;
};
this.changeName = function(newName) {
name = newName;
};
this.getAge = function() {
return age;
};
}
That code does update the parameter (which has no effect at all on the code calling Person). It doesn't create name and age properties at all; instead, it just makes their values accessible via getName and getAge. There's also a function to change name (changeName); but there's no function to change age. People write code like that so that age cannot be changed from outside code created within the Person constructor.
I guess you may misunderstand which parameter you actually change, so I rewrite it like so, holp this helps.
function Person (argument_name, argument_age) {
this.name = argument_name;
this.age = argument_age;
this.changeName = function (argument_change_name) {
this.name = argument_change_name;
}
}
let p1 = new Person ("John", 30);
p1.changeName ("Jane");
console.log(p1);
The this keyword is used to create and assign values to variables in the class. It is again used to create functions, either getters or setters. So in your code this.changeName is a function that when passed a value will change the name of the person.
eg.
var a = 5; // a is an integer
var b = "Han"; //b is a string
var c = function(name){
//code here
} // then c is also a function;
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()
I am trying to learn more about JavaScript OO Programming, but am seeing conflicting methods to create a "Class"-like object. I am wondering if there are any substantial differences in these two methods:
Method 1
function Person(name){
this.name = name;
this.setName = function(val){
this.name = val;
}
this.getName = function(){
return this.name
}
}
var John = new Person("John");
Method 2
function Person(name){
var exports = {};
exports.name = name;
exports.setName = function(val){
this.name = val;
}
exports.getName = function(){
return this.name
}
return exports;
}
var Bob = Person("Bob");
I have seen these two methods used for creating a complex JavsScript object. I have even seen large JS plugins like jQuery use method 2 instead of method 1 to set up their jQuery functions. Is one of these faster or more efficient than the other in any way?
The first one creates an object of the type Person, while the second one creates an object of the type Object. The first one allows you to add members to the prototype of Person.
You can put all the functions in the prototype instead of creating new functions for every instance:
function Person(name){
this.name = name;
}
Person.prototype = {
setName: function(val){
this.name = val;
},
getName: function(){
return this.name
}
}
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 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;
}
};