Subj : Re: Strange Rhino NativeString behavior To : Matt McShane From : Igor Bukanov Date : Sun Oct 24 2004 12:45 pm Matt McShane wrote: > Hello, > > I am having trouble understanding some Rhino behavior, hopefully someone > here can explain for me. > > I have added a function to Object.protoype, let's call it myFunc. Here > is the Java implementation: > > public static Object myFunc(Context cx, Scriptable thisObj, > Object[] args, Function funOb) > { > Object someAttributeValue = thisObj.get("someAttribute",thisObj); > System.out.println(someAttributeValue.toString()); > return Context.getUndefinedValue(); > } > > I am simply assuming that the object has a property called > "someAttribute" and printing it out (I took out null checks, etc. for > clarity) > > This works for the first two of the following tests but not the third. > > var obj = new Object() > obj.someAttribute = "xyz" > obj.myFunc() //prints xyz > > var date = new Date() > date.someAttribute = "xyz" > date.myFunc() //prints xyz > > > var msg = "Hello, world." > msg.someAttribute = "xyz" > msg.myFunc() //prints o.m.j.UniqueTag@1027b4d: NOT_FOUND > > I understand why the someAttribute property in the NativeString test > isn't found - it's because the instance of NativeString on which the > property is "put" is different than the instance passed as thisObj to my > myFunc. In other words, Rhino is creating a different instance of > NativeString with new NativeString("Hello, world.") before passing it to > myFunc. But I don't know why this is. There may be a good reason to use > different instances - but why aren't properties copied over? You hit here JavaScript discrepancy about primitive type != object. ECMAScript standard effectively states that x.y should be implemented via converting x to object and then accessing its properties. If x is string, it is converted using new String(x) so your last example is equivalent to: var msg = "Hello, world." (new String(msg)).someAttribute = "xyz" (new String(msg)).myFunc() //prints o.m.j.UniqueTag@1027b4d: NOT_FOUND Thus any property assignment to primitive string is useless operation since the temporary created String object will be lost. Regards, Igor .