Okay see the following code:
function person(name){
this.name = name;
this.say = function(){
alert(this.name);
}
};
Main = {};
Main.person1 = new person("p1");
Main.person2 = new person("p2");
Main.person3 = new person("p3");
executeSay = function(argument1){
//Implementation
}
What executeSay should do is, call the say method of the given argument, I am not sure how it goes but let me put this way executeSay("person1") should execute Main.person1.say() and so on. I think we can accomplish this by call method but I am not sure about the implementation.
Please don't suggest the following approach
say = function(){
alert(this.name);
}
say.call(Main.person1);
If you already pass the object in the function, you can access all its methods there, so use:
executeSay = function(person){
person.say();
}
and then call this function by, e.g.,
executeSay( Main.person1 );
I'd do it like this:
function Person(name){
this.name = name
}
Person.prototype.say = function () {alert(this.name)}
var main = {
person1: new Person('p1')
, person2: new Person('p2')
, person3: new Person('p3')
}
function executeSay(personStr) {main[personStr].say()}
(Updated to reflect the the string parameter for executeSay)
Let executeSay calls the say method on the argument object:
executeSay = function(person){
person.say();
}
Demo.
Is this not working?
executeSay = function(person){person.say()}
Related
I'm always getting Cannot set property 'saySomething' of undefined but why?
Am I making a mistake somewhere?
var Person = new Object();
Person.prototype.saySomething = function ()
{
console.log("hello");
};
Person.saySomething();
Debugging tip: You get this ..of undefined errors when you try to access some property of undefined.
When you do new Object(), it creates a new empty object which doesn't have a prototype property.
I am not sure what exactly are we trying to achieve here but you can access prototype of function and use it.
var Person = function() {};
Person.prototype.saySomething = function() {
console.log("hello");
};
var aperson = new Person();
aperson.saySomething();
The prototype property exists on functions, not on instantiated objects.
var Person = new Object();
console.log(Person.prototype); // undefined
var Person2 = function () {}
console.log(Person2.prototype); // {}
This is useful because things put on the prototype of a function will be shared by all object instances created with that function (by using new).
var Person = function() {};
Person.prototype.saySomething = function() {
console.log("hello");
};
console.log(
new Person().saySomething === Person.prototype.saySomething // true. they are the same function
);
If all you want is to add a method to the person object, there's no need for a prototype:
var Person = {};
Person.saySomething = function() {
console.log("hello");
};
Person.saySomething();
You can even use object literal syntax:
var Person = {
saySomething: function() {
console.log("hello");
}
};
Person.saySomething();
i was trying out some code thought of posting it, might help others.
<script>
var MODULE = {};
MODULE = (function (my) {
my.anotherMethod = function () {
console.log("hello ");
};
my.newMethod = function(){
console.log("hi new method ");
}
return my;
}(MODULE));
MODULE.anotherMethod();
MODULE.newMethod();
</script>
And please not var MODULE ={}, if this is not initialized with {} then it give cannot set property.
I know i am late to the party but as you see there is no satisfying answer available to the question so i am providing my own.
In your case when you write
var Person = new Object();
you are creating an instance of Object type.
You can add a property using prototype property to the Object, not to the instance of Object.which you can use by the instance laterly.
so you can define like
Object.prototype.saySomething = function ()
{
console.log("hello");
};
now you can call it like this.
Person.saySomething();
You can check here.
var Person = function(name) {
this.canTalk = true;
this.name = name;
};
Person.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name);
}
};
bob = new Person('bob');
bob.greet();
I am working on a Javascript object exercise. My output is not what I expected. Please take a look at my code and give some advise. Here is the code:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models = brand;
};
}
var c = new myFunction ("pc");
c.add("HP");
c.add("DELL");
console.log(c.models);
The output is "DELL"
My expected output is ["HP","DELL"]
Thank you so much for your help!
Change the add function. You want to push the brand into the model. Not set the model to it.
this.add = function (brand){
this.models.push(brand);
};
To add something to an array, you should use the .push() method.
Change your code to:
function myFunction(name) {
this.name = name;
this.models = new Array();
this.add = function (brand){
this.models.push(brand);
};
}
P.S. It is customary to name such constructor type of functions starting with a capital letter.
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.
I have a function name in a string:
var func = "doTest";
I need this function to be applied to the current instance ("this");
So I need it to call:
this.doTest();
How can I do this? I cannot go via window.
Thanks,
Wesley
Just use the construct of object[functionName]();, like so:
function Person() {};
Person.prototype.speak = function() { alert('ohai'); };
var john = new Person, action = 'speak';
john[action]();
Alternative style:
var Person = {
speak: function() { alert('ohai'); },
speakDelegate: function() { var action = 'speak'; this[action](); }
};
Person.speakDelegate();
this[func]();
No need to .call or .apply since context is held in the reference.
For example:
var obj = {
doTest: function(){ console.log(this); },
fn: function(){ var name='doTest'; this[name](); }
};
obj.fn(); // logs the object, proving this has the correct context.
Try the following
var funcObj = this["doTest"];
funcObj.apply(this);
What this does is grab the member named doTest from this. It then executes the function via apply and tells javascript to bind this as this within the function. I think the example is a bit less confusing if you consider the same code on a non-this value
var obj = {
doTest: function() {
console.log("doTest called");
}
};
var doTestFunc = obj["doTest"];
doTestFunc.apply(obj);
In this case the method doTest will be executed with the value obj as this
If you are using jquery you can just do:
$(this)[func]()
I want to use values of the calling object within the jquery code block, but 'this' is mapped to the jquery object and not eh caller! How to solve this PLEASE?
// class
myClass = function (){
// member object
this._localVars = {
_elementClass:'.elem-class',
_dots:null,
_dotStatus:null
};
// member function
this.func1 = function() {
$(this._elementClass).each(function(_index, _element){
// this._localVars._dots[_index] = _element; ... this line throws an error 'this._localVars' is undefined ... as 'this' is html element here and not an object of the calling class
});
};
};
Please suggest how can I use the 'this' inside the jquery code block to refer the variables/objects of the class and not HTML/jQuery.
Thanks
Try saving this object into a local variable
var myObject = this;
$(this._elementClass).each(function(_index, _element){
myObject._localVars._dots[_index] = _element;
});
You can use the jQuery.proxy method to set the value of this that you want.
You pass your function as the first parameter, and the current this as the second.
myClass = function (){
this._localVars = {
_elementClass:'.elem-class',
_dots:[],
_dotStatus:null
};
this.func1 = function() {
$(this._localVars._elementClass).each( $.proxy(function(_index, _element) {
this._localVars._dots[_index] = _element;
}, this));
};
};
var cl = new myClass();
cl.func1();
console.log(cl._localVars._dots);