Find name of property owner in javascript - javascript

An example from some javascript course that I am following:
var Tornado = function(name, cities, degree) {
this.name = name;
this.cities = cities;
this.degree = degree;
};
Tornado.prototype = {
nCities: function() {
return this.cities.length
},
valueOf: function() {
return this.nCities() * this.degree;
},
toString: function() {
return this.cities[0][0].toString() + " " + this.name;
}
}
cities = [["Washington", 1], ["Rotterdam", 2]]
var x = new Tornado("crazy", cities, 3)
console.log(x.nCities())
console.log(x.valueOf())
console.log(x + 16)
console.log(x.toString() + "... wow!")
Object.prototype.findOwnerOfProperty = function(propName) {
var currentObject = this;
while(currentObject !== null) {
if(currentObject.hasOwnProperty(propName)) {
return currentObject;
} else {
currentObject = currentObject.__proto__;
}
}
return "No property found!";
};
console.log(x.findOwnerOfProperty("toString"));
The findOwnerOfProperty function returns the object where the property is defined. This is nice, but it would be nicer to also have the name of that object (Tornado.prototype in this example), how can I do that?

No built-in solution. but you can make a property
this._constructor = arguments.callee.name;
inside Tornado function and make a
getConstructor:function(){
return this._constructor;
}
inside prototype.
BTW , forgot to mention that you should remake
var Tornado = function
to:
function Tornado

Related

Using getter / setter for dynamic object properties

I have an object called status where I want to keep track of any status of a class.
Beside setting various statuses I also want to keep track of how long these have been active. Now instead of defining a second property for every status to track the time, this sounded like a job for getter / setter.
That's where I'm stuck. How do I make them dynamic so they trigger for each property of status?
var Person = function(options) {
this.name = options.name;
var _statusChanged = {};
var _status = {};
// How to make this dynamic?
var expr = "isOnfire";
this.status = {
get [expr]() {
console.log(_statusChanged);
return _status[expr];
},
set [expr](val) {
_status[expr] = val;
_statusChanged[expr] = new Date();
return _status[expr];
}
};
};
var John = new Person({
name: "John"
});
John.status.isOnfire = true;
John.status.hasPinkShirt = true;
console.log(John, John.status.isOnfire, John.status.hasPinkShirt);
If you have a list of these, just create the getters/setters in a loop, e.g.:
this.status = {};
["isOnFire", "hasPinkShirt"].forEach((name) => {
Object.defineProperty(status, name {
get() {
console.log(_statusChanged);
return _status[name];
},
set(val) {
_status[name] = val;
_statusChanged[name] = new Date();
return _status[name];
}
});
});
If they could be anything, then you'll want to use a Proxy object. With a proxy, you can capture all gets/sets without knowing property names in advance:
this.status = new Proxy(_status, {
get(target, propKey, receiver) {
// handle get
return _status[propKey];
},
set(target, propKey, value, receiver) {
// handle set
_status[propKey] = value;
_statusChanged[propKey] = new Date();
return true; // Tells the proxy the assignment worked
}
});
(Or you might use Reflect.get and Reflect.set, but even Firefox doesn't have them yet.)
Here's an article going into proxies in more detail.
Here's an example, but you'll need to run it in a recent version of Firefox because support or Proxy in the wild is still really thin on the ground, and by their nature, you can't shim/polyfill proxies.
(function() {
"use strict";
var _status = {};
var _statusChanged = {};
var status = new Proxy(_status, {
get(target, propKey, receiver) {
snippet.log(propKey + " requested");
return _status[propKey];
},
set(target, propKey, value, receiver) {
snippet.log(propKey + " set to " + value);
_status[propKey] = value;
_statusChanged[propKey] = new Date();
return true; // Tells the proxy the assignment worked
}
});
status.foo = "bar";
snippet.log("foo = " + status.foo);
})();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Until you can use them, you'll need to make setting a status a method call, not an assignment.
You need an object called an ECMAScript 6 Proxy. In Firefox, they're on by default. At one point they were implemented in Chrome under "experimental JavaScript" but they seem to have been removed temporarily; see this ES6 compatibility table.
This code works in Firefox:
var output = function(text) {
var line = document.createElement('div');
line.innerHTML = text;
document.getElementById('output').appendChild(line);
}
var Person = function(options) {
this.name = options.name;
var _status = {};
var _statusChanged = {};
this.status = new Proxy(_status,{
get: function(target,property) {
return target[property];
},
set: function(target,property,value) {
_statusChanged[property] = new Date();
output("set " + property + " to " + value + " at " + _statusChanged[property]);
_status[property] = value;
}
});
this.show = function(property) {
output("Property " + property + " is " + _status[property] + " since " + _statusChanged[property]);
}
};
var John = new Person({
name: "John"
});
John.status.isOnfire = true;
John.status.hasPinkShirt = true;
John.show("isOnfire");
John.show("hasPinkShirt");
<div id="output"></div>
Maybe that would work for you
http://jsfiddle.net/oksbLyqf/16/
var Person = function (options) {
this.name = options.name;
var _statusChanged = {};
var _status = {};
var expr = '';
var addStatusProperty = function (prop) {
expr = prop;
Object.defineProperty(otherStatus, expr, {
get: function () {
console.log(_statusChanged);
return _status[expr];
},
set: function (val) {
_status[expr] = val;
_statusChanged[expr] = new Date();
return _status[expr];
}
});
};
var setStatusProperty = function (prop, val) {
expr = prop;
if (_status[expr]) {
otherStatus[expr] = val;
return _status[expr];
} else {
addStatusProperty(expr);
otherStatus[expr] = val;
return _status[expr];
}
};
var getStatusProperty = function (prop) {
expr = prop;
return _status[expr]
};
this.status = {
addProperty: addStatusProperty,
setProperty: setStatusProperty,
getProperty: getStatusProperty
};
var otherStatus = this.status;
};
var John = new Person({
name: "John"
});
John.status.setProperty('isOnfire', true);
John.status.setProperty('hasPinkShirt', true);
console.log(John, John.status.getProperty('isOnfire'), John.status.getProperty('hasPinkShirt'));

Javascript - Scope and This

I have some code below. the problem I don't understand is why I don't have to refer to 'children' object via this.children but then accessing the firstname or surname, i have to use this.firstname....
Please help me understand why.
function User(first, sur) {
var firstName;
var surName;
var age;
var children = [];
this.firstName = first;
this.surName = sur;
this.getDisplayName = function() {
return this.firstName + ' ' + this.surName;
};
this.getTotalLength = function() {
return (this.firstName.length + this.surName.length);
};
this.displayFullName = function() {
return (this.firstName + ' ' + this.surName);
};
this.changeMaidenname = function(newSurname) {
if (newSurname)
{
this.surName = newSurname;
}
};
this.addChild = function(childUser) {
children.push(childUser);
};
this.numberOfChildren = function() {
return children.length;
};
this.killChild = function(childUser) {
children.forEach(function(item,index)
{
if (item.firstName === childUser.firstName && item.surName === childUser.surName)
{
children.splice(index, 1);
}
}
)
};
};
module.exports.User = User
In js,this keyword is used to create public variables whereas the var limits the scope of that variable to that particular function. :).You cant even access children object unless it is defined this.children=[]

Can't enumerate getters/setters properties

I am working on some reflections code to try to scrape out properties and functions, but I can't seem to get the getters/setters at all.
The reflection code I have for properties is:
Reflector = function() { };
Reflector.getProperties = function(obj) {
var properties = [];
var proto = obj;
while (proto != Object.prototype) {
console.log('Scrapping proto: ', proto);
for (var prop in proto) {
console.log('typeof ' + prop + ": ", typeof obj[prop]);
if (typeof obj[prop] != 'function') {
properties.push(prop);
}
}
proto = Object.getPrototypeOf(proto);
}
return properties;
};
And a sample of it running (with my debug messages) is:
var SimpleTestObject = function() {
this.value = "Test1";
this._hiddenVal = "Test2";
this._readOnlyVal = "Test3";
this._rwVal = "Test4";
};
SimpleTestObject.prototype = {
get readOnlyVal() {
return this._readOnlyVal;
},
get rwVal() {
return this._rwVal;
},
set rwVal(value) {
this._rwVal = value;
},
func1: function() {
// Test
}
};
SimpleTestObject.func2 = function(test) { /* Test */ };
SimpleTestObject.outsideVal = "Test5";
var props = Reflector.getProperties(SimpleTestObject);
console.log('props: ', props);
console.log('Object.getOwnPropertyNames: ', Object.getOwnPropertyNames(SimpleTestObject));
console.log('rwVal property descriptor: ', Object.getOwnPropertyDescriptor(SimpleTestObject, 'rwVal'));
console.log('rwVal (2) property descriptor: ', Object.getOwnPropertyDescriptor(Object.getPrototypeOf(SimpleTestObject), 'rwVal'));
What I expect to see as output to my Reflection.getProperties(SimpleTestObject) is ['readOnlyVal', 'rwVal', 'outsideVal'], but instead I am only seeing outsideVal. Further, when I tried to using getOwnPropertyDescriptor() to see if the rwVal was enumerable, it came back as undefined. So, thinking maybe it somehow got showed into the prototype above, I tried going up a level and still got undefined.
For enumerate the getters please use Object.keys or Object.getOwnPropertiesNames on prototype instead of constructor or/and instance:
function readGetters(obj) {
var result = [];
Object.keys(obj).forEach((property) => {
var descriptor = Object.getOwnPropertyDescriptor(obj, property);
if (typeof descriptor.get === 'function') {
result.push(property);
}
});
return result;
}
var SimpleTestObject = function() {
this.value = "Test1";
this._hiddenVal = "Test2";
this._readOnlyVal = "Test3";
this._rwVal = "Test4";
};
SimpleTestObject.prototype = {
get readOnlyVal() {
return this._readOnlyVal;
},
get rwVal() {
return this._rwVal;
},
set rwVal(value) {
this._rwVal = value;
},
func1: function() {
}
};
SimpleTestObject.func2 = function(test) { /* Test */ };
SimpleTestObject.outsideVal = "Test5";
// For constructor
console.log(readGetters(SimpleTestObject.prototype));
// For instance
var instance = new SimpleTestObject();
console.log(readGetters(Object.getPrototypeOf(instance)));
you can enumerate setter/getter properties by Object.getOwnPropertyNames if you use getter and setter with Object.defineProperty or Object.defineProperties
const _name = Symbol();
const _age = Symbol();
class Dog {
constructor(name, age) {
Object.defineProperties(this, {
name: {
// you can set enumerable true explicitly if you want
//enumerable:true ,
set(value) {
this[_name] = name;
},
get() {
return this[_name];
}
},
age: {
set(value) {
this[_age] = age;
},
get() {
return this[_age];
}
},
book: {
get() {
return "Book"
}
}
});
this.name = name;
this.age = age;
}
}
const dog = new Dog("spike", 3);
console.log(Object.getOwnPropertyNames(dog));

Getter in object isn't returning a value Javascript

I have a problem with return a value from an object.
my object looks like this.
function XYZ(date, startT)
{
var _date=date;
var _startT=startT;
this.get_date = function() {
return _date;
};
this.set_date = function(value) {
_date=value;
};
this.get_startT = function() {
return _startT;
};
this.set_startT = function(value) {
_startT=value;
};
this.toString()
return (_date + " " _startT);
}
then i create an Array like this
jsData[0] =new XYZ("2012-11-11","8:00");
jsData[1] = new XYZ("2012-03-03","8:00");
when i want to use get_date method it didn't return me the value but the get_startT method works fine.
When i show object with .toString method it also show me full object
Please help.
It works if you fix all the syntax errors:
function XYZ(date, startT) {
var _date=date;
var _startT=startT;
this.get_date = function() {
return _date;
};
this.set_date = function(value) {
_date=value;
};
this.get_startT = function() {
return _startT;
};
this.set_startT = function(value) {
_startT=value;
};
}
var jsData = [];
jsData[0] = new XYZ("2012-11-11","8:00");
jsData[1] = new XYZ("2012-03-03","8:00");
display("jsData[0].get_date() = " + jsData[0].get_date());
Output:
jsData[0].get_date() = 2012-11-11
Live Copy | Source
Other than obvious typos, here's what I did:
Put { and } around the function body.
Removed the this.toString() which was non-functional (a no-op, as you didn't store the result anywhere).
Removed the return at the end, because returning a string primitive out of a constructor function is another no-op.
Declared jsData.
Initialized jsData.
You appear to be missing a opening bracket { after
function XYZ(date, startT)
And one at the end of your code. (})
Try adding methods to the function prototype like this:
function XYZ(date, startT) {
this._date = date;
this._startT = startT;
}
XYZ.prototype.get_date = function() {
return this._date;
}
XYZ.prototype.set_date = function(value) {
this._date = value;
}
XYZ.prototype.get_startT = function() {
return this._startT;
}
XYZ.prototype.set_startT = function(value) {
this._startT = value;
}
XYZ.prototype.toString = function() {
return this._date + " " + this._startT;
}
var myXYZ = new XYZ("2012-11-11","8:00");
myXYZ.toString(); // "2012-11-11 8:00"
I tested that in the console and it outputs the final string correctly.

javascript inheritance framework

Is there a small, lightweight solution for javascript class inheritance that will work well on both client and server side (node.js)? I'm not wanting a big library, just something that will allow me to declare a constructor and some methods, then have the ability for a class to inherit that.
John Resig outlines a simple inheritance framework in about 25 lines of code here. I have seen it used to good effect.
You can use it like this:
var Vehicle = Class.extend({
init: function(wheels) {
this.wheels = wheels;
}
});
var Truck = Vehicle.extend({
init: function(hp, wheels) {
this.horsepower = hp;
this._super(wheels);
},
printInfo: function() {
console.log('I am a truck and I have ' + this.horsepower + ' hp.');
}
});
var t = new Truck(4, 350);
t.printInfo();
take a look at https://github.com/ded/klass
I created this small library to use an ExtJs Style ClassManager. It's quite simple yet, but very flexible.
Install via node.js
npm install esf-core
Sample
Esf.define('A', {
a: null,
constructor: function (a) {
// Save var
this.a = a;
// Heyho
console.log('A');
},
foo: function (b) {
console.log('foo - ' + b);
}
});
Esf.define('B', {
b: null,
constructor: function (a, b) {
// Call super constructor
this.callParent(a);
// Save var
this.b = b;
// Heyho
console.log('B');
},
foo: function () {
this.callParent('bar');
}
}, {
extend: 'A'
});
// Use
var b = new B(1, 2);
// or
var b = Esf.create('B', 1, 2);
/*
* Output:
* A
* B
* foo - bar
*/
b.foo();
Repository
https://bitbucket.org/tehrengruber/esf-js-core
I've seen the prototype library used successfully.
I think this is much better than the init hax in the simple inheritance fw:
(function() {
var core = {
require : function(source) {
if ( typeof (source) != "object" || !source)
throw new TypeError("Object needed as source.");
for (var property in source)
if (source.hasOwnProperty(property) && !this.prototype.hasOwnProperty(property))
this.prototype[property] = source[property];
},
override : function(source) {
if ( typeof (source) != "object" || !source)
throw new TypeError("Object needed as source.");
for (var property in source)
if (source.hasOwnProperty(property))
this.prototype[property] = source[property];
},
extend : function(source) {
var superClass = this;
var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {
superClass.apply(this, arguments);
};
newClass.superClass = superClass;
var superClone = function() {
};
superClone.prototype = superClass.prototype;
newClass.prototype = new superClone();
newClass.prototype.constructor = newClass;
if (source)
newClass.override(source);
return newClass;
}
};
core.require.call(Function, core);
Function.create = function (source){
var newClass = source.hasOwnProperty("constructor") ? source.constructor : function() {};
newClass.override(source);
return newClass;
};
})();
The vehicle example with this:
var Vehicle = Function.create({
constructor : function(wheels) {
this.wheels = wheels;
}
});
var Truck = Vehicle.extend({
constructor : function(hp, wheels) {
this.horsepower = hp;
Vehicle.call(this, wheels);
},
printInfo : function() {
console.log('I am a truck and I have ' + this.horsepower + ' hp.');
}
});
var t = new Truck(4, 350);
t.printInfo();
I created a very lightweight library that works in-browser and in node.js. Its a super easy-to-use, bloatless library:
https://github.com/fresheneesz/proto
Example:
var Person = proto(function() { // prototype builder
this.init = function(legs, arms) { // constructor
this.legs = legs
this.arms = arms
}
this.getCaughtInBearTrap = function() { // instance method
this.legs -= 1
}
this.limbs = function() {
return this.arms + this.legs
}
})
var Girl = proto(Person, function() { // inheritance
this.haveBaby = function() {
return Person(2,2)
}
})
var g = Girl(2,2) // instantiation
g.getCaughtInBearTrap()
console.log("Girl has "+g.limbs()+" limbs")
console.log(": (")

Categories

Resources