开发者

JavaScript prototype(ing) question

开发者 https://www.devze.com 2022-12-29 12:48 出处:网络
Trying to grasp Prototyping in Javascript. Trying to create my own namespace to extend the String object in JavaScript.

Trying to grasp Prototyping in Javascript. Trying to create my own namespace to extend the String object in JavaScript.

Here is what I have so far (a snippet):

var ns {
 alert: function() {
  alert (this);
 }
}
String.prototype.$ns = ns;

As you can see, I am trying to place what will be a series of functions into the ns namespace. So I can execute a command like 开发者_开发问答this:

"hello world".$ns.alert();

But the problem is, the this doesn't reference the text being sent (in this case, "hello world"). What I get is an alert box with the following:

[object Object]

Not having a full grasp of the object-oriented nature of JavaScript, I am at a loss, but I am guessing I am missing something simple.

Does anyone know how to achieve this (get the source text from the nested object)? Short of that, I am left with having to do procedural programming ( ns.alert("hello world"); ) which I am trying to avoid.

Thanks -


This is happening because when you invoke a reference, its base object is set as the this value of the invoked method (more technical details here).

So when you invoke "hello world".$ns.alert(); the this value inside your alert method, will refer to "hello world".$ns, which is String.prototype.$ns.

I don't think adding object levels (namespaces) inside the prototype of built-in objects can be useful, I usually recommend to not modify objects you don't own.

0

精彩评论

暂无评论...
验证码 换一张
取 消