package com.drawbridge.jsengine.jsobjects;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
* JavaScript objects have properties. A property can be a JSType (i.e. a function as well as a literal).
* @author Alistair Stead
*
*/
public class JSObject implements JSType
{
protected HashMap<String, JSType> properties = new HashMap<String, JSType>();
public JSObject(){
//Add prototype here
//TODO prototype should be a new property of each object
addProperty("hasOwnProperty", new JSNativeFunction(this, "hasOwnProperty", new Class<?>[] {JSObject.class, JSString.class}));
addProperty("prototype", new JSNativeFunction(this, "prototype", null));
addProperty("constructor", new JSObject(false));
}
public JSObject(boolean constructor){
if(constructor)
{
addProperty("hasOwnProperty", new JSNativeFunction(this, "hasOwnProperty", new Class<?>[] {JSObject.class, JSString.class}));
addProperty("prototype", new JSNativeFunction(this, "prototype", null));
addProperty("constructor", new JSObject(false));
}
else{
addProperty("hasOwnProperty", new JSNativeFunction(this, "hasOwnProperty", new Class<?>[] {JSObject.class, JSString.class}));
addProperty("prototype", new JSNativeFunction(this, "prototype", null));
}
}
public JSType getProperty(String name){
return properties.get(name);
}
public void addProperty(String name, JSType value){
properties.put(name, value);
}
@Override
public String toString(){
String result = "";
Set<String> keys = properties.keySet();
Iterator<String> it = keys.iterator();
while(it.hasNext()){
String name = it.next();
Object obj = properties.get(name);
result += " {" + name + ":" + obj.toString() + "}";
}
return result;
}
@Override
public boolean equals(Object object){
if(object instanceof JSObject){
JSObject dbObject = (JSObject) object;
if(dbObject.properties.size() == properties.size()){
Set<String> keys = properties.keySet();
Iterator<String> it = keys.iterator();
while(it.hasNext()){
String name = it.next();
Object obj = properties.get(name);
if(dbObject.properties.get(name).equals(obj)){
}
else{
return false;
}
}
}
else{
return false;
}
}
else{
return false;
}
return true;
}
}