I wrote the following test code, I want obj.my().showTxt() to display “test1”, but nothing is displayed, what error did I make?
Thanks!
<html>
<body>
Primitive and String Objects
<script type="text/javascript">
function Class1() {
this.showTxt = function () { alert(this.name) }
}
Object.prototype.my = Class1;
var obj = new Object();
obj.name = "test1";
obj.my().showTxt();
</script>
</body>
</html>
It seems like the problem is that your function
Class1was not returning an instance of itself.Is this close to what you were trying to achieve?
http://jsfiddle.net/a4ZgF/
The function Class1 returns undefined (as it has no return statement). Therefore Object.prototype.my is equal to undefined which does not have a function called showTxt(). By return this you have now returned the object which has that function on it.
Using your browser’s debugger will help a lot to step through each line and see what is going on.