Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script type="text/javascript">//<![CDATA[
- alert("I'm evaluated in the initial global execution context!");
- setTimeout(function () {
- alert("I'm NOT evaluated in the initial global execution context.");
- }, 1);
- //]]></script>
- function doWork(callbackfn, thisArg) {
- //...
- if (callbackfn != null) callbackfn.call(thisArg);
- }
- function MyType() {
- this.someData = "a string";
- }
- var instance = new MyType();
- // Kind of like the following, but there are more steps involved:
- // var instance = {};
- // MyType.call(instance);
- <script type="text/javascript">
- if (true) {
- // Line A
- }
- </script>
- <script type="text/javascript">
- var obj = {
- someData: "a string"
- };
- function myFun() {
- // Line B
- }
- obj.staticFunction = myFun;
- obj.staticFunction();
- </script>
- <script type="text/javascript">
- var obj = {
- myMethod : function () {
- // Line C
- }
- };
- var myFun = obj.myMethod;
- myFun();
- </script>
- <script type="text/javascript">
- function myFun() {
- // Line D
- }
- var obj = {
- myMethod : function () {
- eval("myFun()");
- }
- };
- obj.myMethod();
- </script>
- <script type="text/javascript">
- function myFun() {
- // Line E
- }
- var obj = {
- someData: "a string"
- };
- myFun.call(obj);
- </script>
- document.write(this); //[object Window]
- function f1()
- {
- return this;
- }
- document.write(f1()); //[object Window]
- function f()
- {
- return this;
- }
- document.write(window.f()); //[object Window]
- var obj = {
- name: "obj",
- f: function () {
- return this + ":" + this.name;
- }
- };
- document.write(obj.f()); //[object Object]:obj
- var obj = {
- name: "obj1",
- nestedobj: {
- name:"nestedobj",
- f: function () {
- return this + ":" + this.name;
- }
- }
- }
- document.write(obj.nestedobj.f()); //[object Object]:nestedobj
- var obj1 = {
- name: "obj1",
- }
- function returnName() {
- return this + ":" + this.name;
- }
- obj1.f = returnName; //add method to object
- document.write(obj1.f()); //[object Object]:obj1
- var context = "global";
- var obj = {
- context: "object",
- method: function () {
- function f() {
- var context = "function";
- return this + ":" +this.context;
- };
- return f(); //invoked without context
- }
- };
- document.write(obj.method()); //[object Window]:global
- /*********************************************************************
- 1. When you add variable to the function using this keyword, it
- gets added to the function prototype, thus allowing all function
- instances to have their own copy of the variables added.
- *********************************************************************/
- function functionDef()
- {
- this.name = "ObjDefinition";
- this.getName = function(){
- return this+":"+this.name;
- }
- }
- obj1 = new functionDef();
- document.write(obj1.getName() + "<br />"); //[object Object]:ObjDefinition
- /*********************************************************************
- 2. Members explicitly added to the function protorype also behave
- as above: all function instances have their own copy of the
- variable added.
- *********************************************************************/
- functionDef.prototype.version = 1;
- functionDef.prototype.getVersion = function(){
- return "v"+this.version; //see how this.version refers to the
- //version variable added through
- //prototype
- }
- document.write(obj1.getVersion() + "<br />"); //v1
- /*********************************************************************
- 3. Illustrating that the function variables added by both above
- ways have their own copies across function instances
- *********************************************************************/
- functionDef.prototype.incrementVersion = function(){
- this.version = this.version + 1;
- }
- var obj2 = new functionDef();
- document.write(obj2.getVersion() + "<br />"); //v1
- obj2.incrementVersion(); //incrementing version in obj2
- //does not affect obj1 version
- document.write(obj2.getVersion() + "<br />"); //v2
- document.write(obj1.getVersion() + "<br />"); //v1
- /*********************************************************************
- 4. `this` keyword refers to the immediate parent object. If you
- nest the object through function prototype, then `this` inside
- object refers to the nested object not the function instance
- *********************************************************************/
- functionDef.prototype.nestedObj = { name: 'nestedObj',
- getName1 : function(){
- return this+":"+this.name;
- }
- };
- document.write(obj2.nestedObj.getName1() + "<br />"); //[object Object]:nestedObj
- /*********************************************************************
- 5. If the method is on an object's prototype chain, `this` refers
- to the object the method was called on, as if the method was on
- the object.
- *********************************************************************/
- var ProtoObj = { fun: function () { return this.a } };
- var obj3 = Object.create(ProtoObj); //creating an object setting ProtoObj
- //as its prototype
- obj3.a = 999; //adding instance member to obj3
- document.write(obj3.fun()+"<br />");//999
- //calling obj3.fun() makes
- //ProtoObj.fun() to access obj3.a as
- //if fun() is defined on obj3
- var myname = "global context";
- function SimpleFun()
- {
- this.myname = "simple function";
- }
- var obj1 = new SimpleFun(); //adds myname to obj1
- //1. `new` causes `this` inside the SimpleFun() to point to the
- // object being constructed thus adding any member
- // created inside SimipleFun() using this.membername to the
- // object being constructed
- //2. And by default `new` makes function to return newly
- // constructed object if no explicit return value is specified
- document.write(obj1.myname); //simple function
- var ProtoObj = {
- fun: function () {
- return this.a;
- }
- };
- //Object.create() creates object with ProtoObj as its
- //prototype and assigns it to obj3, thus making fun()
- //to be the method on its prototype chain
- var obj3 = Object.create(ProtoObj);
- obj3.a = 999;
- document.write(obj3.fun()); //999
- //Notice that fun() is defined on obj3's prototype but
- //`this.a` inside fun() retrieves obj3.a
- function add(inc1, inc2)
- {
- return this.a + inc1 + inc2;
- }
- var o = { a : 4 };
- document.write(add.call(o, 5, 6)+"<br />"); //15
- //above add.call(o,5,6) sets `this` inside
- //add() to `o` and calls add() resulting:
- // this.a + inc1 + inc2 =
- // `o.a` i.e. 4 + 5 + 6 = 15
- document.write(add.apply(o, [5, 6]) + "<br />"); //15
- // `o.a` i.e. 4 + 5 + 6 = 15
- var g = add.bind(o, 5, 6); //g: `o.a` i.e. 4 + 5 + 6
- document.write(g()+"<br />"); //15
- var h = add.bind(o, 5); //h: `o.a` i.e. 4 + 5 + ?
- document.write(h(6) + "<br />"); //15
- // 4 + 5 + 6 = 15
- document.write(h() + "<br />"); //NaN
- //no parameter is passed to h()
- //thus inc2 inside add() is `undefined`
- //4 + 5 + undefined = NaN</code>
- <script>
- function clickedMe() {
- alert(this + " : " + this.tagName + " : " + this.id);
- }
- document.getElementById("button1").addEventListener("click", clickedMe, false);
- document.getElementById("button2").onclick = clickedMe;
- document.getElementById("button5").attachEvent('onclick', clickedMe);
- </script>
- <h3>Using `this` "directly" inside event handler or event property</h3>
- <button id="button1">click() "assigned" using addEventListner() </button><br />
- <button id="button2">click() "assigned" using click() </button><br />
- <button id="button3" onclick="alert(this+ ' : ' + this.tagName + ' : ' + this.id);">used `this` directly in click event property</button>
- <h3>Using `this` "indirectly" inside event handler or event property</h3>
- <button onclick="alert((function(){return this + ' : ' + this.tagName + ' : ' + this.id;})());">`this` used indirectly, inside function <br /> defined & called inside event property</button><br />
- <button id="button4" onclick="clickedMe()">`this` used indirectly, inside function <br /> called inside event property</button> <br />
- IE only: <button id="button5">click() "attached" using attachEvent() </button>
- this
- this
- this
- function foo() {
- console.log("bar");
- console.log(this);
- }
- foo(); // calling the function
- var myObj = {key: "Obj"};
- myObj.logThis = function () {
- // I am a method
- console.log(this);
- }
- myObj.logThis(); // myObj is logged
- // continuing with the previous code snippet
- var myVar = myObj.thisMethod;
- myVar();
- // logs either of window/global/undefined based on mode of operation
- var el = document.getElementById('idOfEl');
- el.addEventListener('click', function() { console.log(this) });
- // the function called by addEventListener contains this as the reference to the element
- // so clicking on our element would log that element itself
- function Person (name) {
- this.name = name;
- this.sayHello = function () {
- console.log ("Hello", this);
- }
- }
- var awal = new Person("Awal");
- awal.sayHello();
- // In `awal.sayHello`, `this` contains the reference to the variable `awal`
- function foo () { console.log (this, arguments); }
- var thisArg = {myObj: "is cool"};
- foo.call(thisArg, 1, 2, 3);
- foo.apply(thisArg, [1,2,3])
- function foo (a, b) {
- console.log (this, arguments);
- }
- var thisArg = {myObj: "even more cool now"};
- var bound = foo.bind(thisArg, 1, 2);
- console.log (typeof bound); // logs `function`
- console.log (bound);
- /* logs `function () { native code }` */
- bound(); // calling the function returned by `.bind`
- // logs `{myObj: "even more cool now"}, [1, 2]`
- var myObj = {
- hello: function () {
- return "world"
- },
- myMethod: function () {
- // copy this, variable names are case-sensitive
- var that = this;
- // callbacks ftw o/
- foo.bar("args", function () {
- // I want to call `hello` here
- this.hello(); // error
- // but `this` references to `foo` damn!
- // oh wait we have a backup o/
- that.hello(); // "world"
- });
- }
- };
- var person = {
- firstName: "Penelope",
- lastName: "Barrymore",
- fullName: function () {
- // We use "this" just as in the sentence above:
- console.log(this.firstName + " " + this.lastName);
- // We could have also written:
- console.log(person.firstName + " " + person.lastName);
- }
- }
- function foo() {
- // return an arrow function
- return (a) => {
- // `this` here is lexically inherited from `foo()`
- console.log(this.a);
- };
- }
- var obj1 = { a: 2 };
- var obj2 = { a: 3 };
- var bar = foo.call(obj1);
- bar.call( obj2 ); // 2, not 3!
- function someKindOfFunction() {
- this.style = 'foo';
- }
- <script type="text/javascript">
- console.log(this === window); // true
- var foo = "bar";
- console.log(this.foo); // "bar"
- console.log(window.foo); // "bar"
- >this
- { ArrayBuffer: [Function: ArrayBuffer],
- Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
- Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
- ...
- >global === this
- true
- \test.js
- console.log(this); \ {}
- console.log(this === global); \ fasle
- <script type="text/javascript">
- foo = "bar";
- function testThis() {
- this.foo = "foo";
- }
- console.log(this.foo); //logs "bar"
- testThis();
- console.log(this.foo); //logs "foo"
- </script>
- <script type="text/javascript">
- foo = "bar";
- function testThis() {
- "use strict";
- this.foo = "foo";
- }
- console.log(this.foo); //logs "bar"
- testThis(); //Uncaught TypeError: Cannot set property 'foo' of undefined
- </script>
- <script type="text/javascript">
- foo = "bar";
- function testThis() {
- this.foo = "foo";
- }
- console.log(this.foo); //logs "bar"
- new testThis();
- console.log(this.foo); //logs "bar"
- console.log(new testThis().foo); //logs "foo"
- </script>
- function Thing() {
- console.log(this.foo);
- }
- Thing.prototype.foo = "bar";
- var thing = new Thing(); //logs "bar"
- console.log(thing.foo); //logs "bar"
- function Thing() {
- this.things = [];
- }
- var thing1 = new Thing();
- var thing2 = new Thing();
- thing1.things.push("foo");
- console.log(thing1.things); //logs ["foo"]
- console.log(thing2.things); //logs []
- var obj = {
- foo: "bar",
- logFoo: function () {
- console.log(this.foo);
- }
- };
- obj.logFoo(); //logs "bar"
- function Listener() {
- document.getElementById("foo").addEventListener("click",
- this.handleClick);
- }
- Listener.prototype.handleClick = function (event) {
- console.log(this); //logs "<div id="foo"></div>"
- }
- var listener = new Listener();
- document.getElementById("foo").click();
- function Listener() {
- document.getElementById("foo").addEventListener("click",
- this.handleClick.bind(this));
- }
- Listener.prototype.handleClick = function (event) {
- console.log(this); //logs Listener {handleClick: function}
- }
- var listener = new Listener();
- document.getElementById("foo").click();
- <div id="foo" onclick="console.log(this);"></div>
- <script type="text/javascript">
- document.getElementById("foo").click(); //logs <div id="foo"...
- </script>
- function Thing () {
- }
- Thing.prototype.foo = "bar";
- Thing.prototype.logFoo = function () {
- eval("console.log(this.foo)"); //logs "bar"
- }
- var thing = new Thing();
- thing.logFoo();
- function Thing () {
- }
- Thing.prototype.foo = "bar";
- Thing.prototype.logFoo = function () {
- with (this) {
- console.log(foo);
- foo = "foo";
- }
- }
- var thing = new Thing();
- thing.logFoo(); // logs "bar"
- console.log(thing.foo); // logs "foo"
- <div class="foo bar1"></div>
- <div class="foo bar2"></div>
- <script type="text/javascript">
- $(".foo").each(function () {
- console.log(this); //logs <div class="foo...
- });
- $(".foo").on("click", function () {
- console.log(this); //logs <div class="foo...
- });
- $(".foo").each(function () {
- this.click();
- });
- </script>
- var val = "window.val"
- var obj = {
- val: "obj.val",
- innerMethod: function () {
- var val = "obj.val.inner",
- func = function () {
- var self = this;
- return self.val;
- };
- return func;
- },
- outerMethod: function(){
- return this.val;
- }
- };
- //This actually gets executed inside window object
- console.log(obj.innerMethod()()); //returns window.val
- //Breakdown in to 2 lines explains this in detail
- var _inn = obj.innerMethod();
- console.log(_inn()); //returns window.val
- console.log(obj.outerMethod()); //returns obj.val
- var status = 1;
- var helper = {
- status : 2,
- getStatus: function () {
- return this.status;
- }
- };
- var theStatus1 = helper.getStatus(); //line1
- console.log(theStatus1); //2
- var theStatus2 = helper.getStatus;
- console.log(theStatus2()); //1
- function Person(name){
- this.personName = name;
- this.sayHello = function(){
- return "Hello " + this.personName;
- }
- }
- var person1 = new Person('Scott');
- console.log(person1.sayHello()); //Hello Scott
- var person2 = new Person('Hugh');
- var sayHelloP2 = person2.sayHello;
- console.log(sayHelloP2()); //Hello undefined
- function testFunc() {
- this.name = "Name";
- this.myCustomAttribute = "Custom Attribute";
- return this;
- }
- var whatIsThis = testFunc();
- console.log(whatIsThis); //window
- var whatIsThis2 = new testFunc();
- console.log(whatIsThis2); //testFunc() / object
- console.log(window.myCustomAttribute); //Custom Attribute
- <script type="application/javascript">
- function click_handler() {
- alert(this); // alerts the window object
- }
- </script>
- <button id='thebutton' onclick='click_handler()'>Click me!</button>
- <script type="text/javascript" language="javascript">
- $('#tbleName tbody tr').each(function{
- var txt='';
- txt += $(this).find("td").eq(0).text();
- \same as above but synatx different
- var txt1='';
- txt1+=$('#tbleName tbody tr').eq(0).text();
- alert(txt1)
- });
- </script>
- $('#a').click(function(){
- console.log($(this).attr('href'));
- });
Add Comment
Please, Sign In to add comment