I am working with createjs library.
I have the following class:
class Person {
constructor(){
this.name = 'John';
}
set updateName(event){
this.name += event.key;
}
}
Next, I instantiate the object like this:
var human = new Person();
I am trying to update the name of the person upon each keystroke like this:
window.addEventListener.on('keydown', human.updateName);
However, I get an error of "Cannot read property 'handleEvent' of undefined".
human.updateName attempts to read the updateName property. Since you haven't defined a getter for it, the result of that is undefined. Apparently whatever you're passing it to (window.addEventListener.on) expects to be passed something other than undefined.
To pass the actual setter function is a bit tricky, you have to get access to it via getOwnPropertyDescriptor and then pass it in:
window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set);
In order to ensure that the right person was updated, you'd probably need bind as well:
window.addEventListener.on('keydown', Object.getOwnPropertyDescriptor(human, "updateName").set.bind(human));
Alternately, it would be rather simpler just to use an arrow function as glue:
window.addEventListener.on('keydown', e => {
human.updateName = e;
});
Side note: updateName is the kind of name you'd give a method, not a property. Normally, a property would be called simply name.
Perhaps you intended it to be a method instead? If so:
class Person {
constructor(){
this.name = 'John';
}
updateName(event){ // No `set` on this line
this.name += event.key;
}
}
...and
window.addEventListener.on('keydown', human.updateName.bind(human));
or
window.addEventListener.on('keydown', e => {
human.updateName(e);
});
Related
I have this class
class Dark {
constructor(name) {
this.name = name;
}
destroy() {
console.log("method called")
console.log(this);
}
}
const DarkObject = new Dark('DarkObject');
const copyDarkObject = {destroy: DarkObject.destroy}
console.log(copyDarkObject.destroy())
//> method called
// > undefined
I stored the reference of the class method to the key of a other Object
const copyDarkObject = { destroy: DarkObject.destroy };
the created Object is not the owner of the method so the return is undefined thats clear to me but I can still invoke the method from the key with console.log(copyDarkObject.destroy())
how is that possible ?
the created Object is not the owner of the method so the return is undefined
No. The statement
console.log(copyDarkObject.destroy())
logs undefined because the destroy method doesn't return anything (since it doesn't use a return statement).
The statement
console.log(this)
in the destroy method will log your copyDarkObject, because destroy was called on copyDarkObject.
And that's why the log says:
method called
Object { destroy: destroy() } // the object destroy was invoked on
undefined // the return value of destoy
Class keyword in JavaScript is just syntactic sugar.
Under the hood it is still prototype based inheritance/system, which allows some extra flexibility.
What exactly happens in your code:
You see returned value undefined - this is correct, because you never return anything from destroy() and Js by default "returns" undefined from functions.
You create a new object giving it one property, which is a reference to darkObject.destroy - value of this pointer/reference in Js depends on how function was called. You can read up on MDN on how built-in function like bind() or apply or call work. In this case when you call destroy on copyOfDarkObject, this points to copyOfDarkObject
class Dark {
constructor(name) {
this.name = name;
}
destroy() {
console.log('I am calling destroy on', this);
return `I am ${this.name}`;
}
}
const darkObject = new Dark('DarkObject');
const copyOfDarkObject = {destroy: darkObject.destroy}
console.log('returned value', copyOfDarkObject.destroy());
console.log('returned value', darkObject.destroy());
console.log(copyOfDarkObject instanceof Dark);
console.log(darkObject instanceof Dark);
Some extra info:
While logging this you can see, that copyOfDarkObject has one property called destroy, but darkObject only one called name. It is so, because destroy method exists on darkObject prototype and you don't see it directly on the object.
I was learing prototypes in Javascript and got a lot about their usages. But I'm confused about the following that how it didn't work.
function Employee(name)
{
this.name = name;
}
Employee.prototype.code = "SIMPLE";
Employee.prototype.getName = function()
{
return this.name;
}
var a = new Employee("Manish");
var b = new Employee("Vikash");
a.__proto__.code // SIMPLE
a.__proto__.getName() // Undefined
Why we can't access a function on __proto__ while a.__proto__ == Employee.prototype returns true.
The context ( aka this ) is determined in javascript when you call a function. So here:
a.__proto__.getName()
the context is a.__proto __ , and that has not a name property, so it returns undefined. Here:
a.getName()
you call getName with the context being a, and a has a name...
You can access the function on the __proto__ object like you expect - but you're getting this behavior because you lose the binding to this when you call it this way so the function is not returning what you expect. The value of this is determed by the calling context. For the purpose of experimenting, you can try adding the binding back like this:
a.__proto__.getName.bind(a)()
// Manish
// or
a.__proto__.getName.call(b)
// Vikash
I try to override a method and script is:
function wrapper(target) {
target.doABC = function () {
alert('in wrapper');
};
return target;
}
function Model() {
wrapper(this);
}
Model.prototype.doABC = function () {
alert('in Model');
};
var a = new Model();
a.doABC();
The result is 'in wrapper'. I don't know why?
Any JavaScript object has own and inherited properties. Own are those defined directly on the instance and inherited are taken from the prototype object.
When using a property accessor, JavaScript first searches in object's own properties list. If the property is not found, it searches in object's prototype chain.
In your example, the wrapper() method defines on object instance an own property doABC, which is a function that alerts 'in wrapper'. Even if the object has a prototype with the same property doAbc that alerts 'in Model', JavaScript anyway will use the own property.
function wrapper(target) {
// Define an own property "doABC"
target.doABC = function () {
alert('in wrapper');
};
return target;
}
function Model() {
wrapper(this);
}
// Define an inherited property "doABC"
Model.prototype.doABC = function () {
alert('in Model');
};
var a = new Model();
//Use the own property "doABC". The inherited "doABC" is ignored.
a.doABC();
As an addition, the own property can be removed using delete operator. After deletion, the object will use the inherited property.
// delete the own property "doABC"
delete a['doABC'];
// the inherited "doABC" will be used. Alerts "in Model"
a.doABC();
Check the complete working demo.
Let me see if I can explain:
You have two separate versions of doABC here.
Your target.doABC creates a function specific to that instance of your Model and each Model get its own doABC.
Because Model has a doABC, the JavaScript engine has no need to look 'up the chain' for something else, hence it will never look for the Model.prototype.doABC version.
You can see this by adding these lines:
Model.prototype.doXYZ = function () {
alert('in Model');
};
and calling
a.doXYZ();
Since a doesn't have its own doXYZ then, and only then, will it look up the chain and see the method in the prototype.
I'm having trouble achieving something in Javascript, and also having trouble explaining it. I'm writing an API and I want the developer to be able to write the following code:
dashboard('name1').createPanel('name2');
The problem is I can't figure out a way to create a function called "dashboard" (which accepts an argument 'name1') while also providing a prototype called createPanel.
You have functions and object. An example:
// A normal function
function dashboard(name) {
}
dashboard("name1");
You can also prototype this function if you do a new you will have to object of class dashboard. So the example:
function dashboard( name ) {
// As class
this.name = name;
}
dashboard.Prototype.createPanel = function(name) {
this.name = name;
return this; // return the reference
}
var x = new dashboard("name1"); // create object
x.createPanel( "Name2" );
// x.name will be "Name2"
What you want is chaining functions. All you need to do is return the object where you want to call the next function from. If you return this every time you can chain functions of that object like:
// extending the class with addProperty for chainging example
dashboard.Prototype.addProperty = function(key, value){
this[key] = value;
return this; // To enable chaining, return reference
}
var x = new dashboard("name1");
x.createPanel("Niels").addProperty("A", "B").addProperty("B", "C");
We can chain on and on. All you need to do is return the reference where you want to continue chaining from (normally the this object). But can be every object you want.
I have this class where I have a private property and a public method for access:
Person = function () {
this.Name = "asd";
var _public = new Object();
_public.Name = function (value) {
if (value == undefined) { //Get
return this.Name
} else {
this.Name = value; //Set
}
};
return _public;
};
I want to force the context in _public.Name for access a this.Name.
I know the technique of closure, but I want to see if I can force a context.
I found a technique to do it, extend object Function:
Function.prototype.setScope = function (scope) {
var f = this;
return function () {
f().apply(scope);
}
}
And my class becomes:
Person = function () {
this.Name = "asd";
var _public = new Object();
_public.Name = function (value) {
if (value == undefined) {
return this.Name
} else {
this.Name = value;
}
}.setScope(this);
return _public;
};
So I can force correctly the context, but I can not pass value and can not, however, return this.Name.
Not
f().apply(scope);
just
f.apply(scope);
(No () after f.) You want to use the apply function on the function f object, not call the function f and access apply on its return value.
To also pass on the arguments that your function in setScope receives, add this:
f.apply(scope, arguments);
arguments is an implicit argument to all functions, which is a pseudo-array of the actual arguments passed to the function at runtime. apply accepts any array-like thing as its second parameter to specify the arguments to use when calling the underlying function.
I'd also have it return the return value:
return f.apply(scope, arguments);
So setScope becomes:
Function.prototype.setScope = function (scope) {
var f = this;
return function () {
return f.apply(scope, arguments);
}
}
Live example
Note that the usual name for this function, and the name it has in the new ECMAScript5 standard, is bind (Section 15.3.4.5; ECMAScript5's bind also lets you curry arguments, which isn't done by this implementation). setScope is a particularly unfortunate name, because it doesn't set the scope, it sets the context.
Having said all that, there's no reason you need setScope in your Person constructor. You can just do this:
Person = function () {
var self = this;
this.Name = "asd";
var _public = new Object();
_public.Name = function (value) {
if (value == undefined) {
return self.Name;
} else {
self.Name = value;
}
};
return _public;
};
Live example
But using bind (aka setScope) can be useful in places where you don't want a new closure over the context in which you're doing it.
Off-topic: The way you're specifying Person will break certain things people might expect to work, such as:
var p = new Person();
alert(p instanceof Person); // Expect "true", but in your case will be "false"
...because you're replacing the object new created for you, but returning a different object out of your constructor (which overrides the default).
Rather than creating a new object and returning that in your constructor, allow the object constructed for you by new to be the object (and thus the Person relationship is maintained), but you can still get truly private variables and use accessors:
function Person() {
// Private variable
var name = "asd";
// Accessor function
this.Name = function(value) {
if (typeof value === "undefined") {
return name;
}
name = value;
};
}
Live example
As you can see, this is dramatically simpler, and it preserves the instanceof relationship. Note that we're not qualifying our references to name within Name at all, and so we're using the local variable in the constructor call in which our Name function, which closes over it, was created.
I've also taken the liberty there of giving the constructor function a name, because I'm not a fan of anonymous functions. I should have given the accessor a name as well:
function Person() {
// Private variable
var name = "asd";
// Accessor function
this.Name = Person_Name;
function Person_Name(value) {
if (typeof value === "undefined") {
return name;
}
name = value;
}
}
Off-topic 2: The overwhelming convention in JavaScript code is to use initial caps on function names only for constructor functions (like Person), and not on other kinds of functions (like Name). You're free to do whatever you like, of course, but I thought I'd mention the convention, as it makes it easier for other people to read your code.
Worth noting: All of these techniques result in every single Person object having its own copy of the accessor function. If there are going to be a lot of these objects, that could be a memory issue. If there are only going to be a few, that's fine.
First thing, I think the correct way to go about this is the "closure" method, as the syntax is easier and simpler to understand and makes more sense and most object oriented code written in Javascript is written that way. Another thing to note is that in your method, the "private" member can be accessed from outside by accessing Person.Name (instead of (new Person()).Name).
That being said, it seems that you want something like Prototype.JS's bind method, which allows you to bind a function reference as a method call to a specific object, and also passes all the arguments correctly (including allowing preloaded arguments).
Look at Prototype.JS source for the complete implementation, but a simple implementation of this semantic might look like this:
Function.prototype.bind = function(context) {
var callee = this;
var args = Array.prototype.slice.call(arguments,1);
return function() {
var newargs = args.concat(Array.prototype.slice.call(arguments,0));
return callee.apply(context, newargs);
};
};
It is difficult to understand what you are trying to achieve. But if I guess that you are trying to create a Person class with a name method to get/set the person's name, here is my suggestion:
function Person() {
this._name = undefined; // not required but is better than assigning a fake name
return this;
}
Person.prototype.name = function( _name ) {
if ( _name === undefined ) return this._name; // get
return this._name = _name; // set
}
Note that I have defined the name function with a lower case first letter. This is standard practice in JavaScript where only constructors are usually capitalized. To use this class you do:
person = new Person();
person.name( "Ermes Enea Colella" );
alert( person.name ); // displays "Ermes Enea Colella"
There is no need to bind any context with this method, so you may be looking for something else. If you can clarify your need, I'll be happy to edit my answer.
I hope this helps.