Is it possible to access JSON properties with relative syntax when using certain JSON functions?

// JavaScript JSON
var myCode = 
{
   message : "Hello World",

   helloWorld : function()
   {
     alert(this.message);
   }
};
myCode.helloWorld();

The above JavaScript code will warn 'undefined'.

To make it real, the code should look like this: (note the literal path to myCode.message)

// JavaScript JSON
var myCode = 
{
   message : "Hello World",

   helloWorld : function()
   {
     alert(myCode.message);
   }
};
myCode.helloWorld();

My question is ... if I declare functions using json this way, is there some kind of "relative" way to access myCode.message or is it only possible using the literal path of the myCode.message namespace?

+3
source share
3 answers

this helloWorld myCode, myCode.helloWorld();

, , this .

myCode myCode.helloWorld.

, this , , , , :

myFunc();

this myFunc .

new:

var obj = new MyFunc();

this myFunc .

this , call apply:

function test () {
  return this + " World";
}
test.call("Hello"); // "Hello World"

, JSON, JSON - , , JavaScript Literal, :

{ foo: "bar" }

JavaScript, JSON, JSON , , , JSON.

+6

.

, JSON. , , - . JSON - .

-, , .

call() apply() -, this window.

myCode , " " . , call() apply(), . , this window, undefined ( window.message undefined).

- . , call() apply().

var myCode = 
{
   message : "Hello World",

   helloWorld : function()
   {
     alert( this.message );
   }
};
myCode.helloWorld.call( myCode );

, Javascript, myCode this, .

- myCode .

var myCode = function()
{
  this.message = 'Hello World';
  this.helloWorld = function()
  {
    alert( this.message );
  }
}
var mc = new myCode();
mc.helloWorld();

a >

0

CMS hit the nail on the head, if you want more information, you can check http://www.scottlogic.co.uk/blog/chris/2010/05/what-is-this/

0
source

Source: https://habr.com/ru/post/1744246/


All Articles