Cara menggunakan execution context javascript

Pada artikel ini, kita akan berbicara tentang topik yang menarik dan agak membingungkan. Ini adalah kata kunci ‘ini’ dalam bahasa pemrograman Javascript.

Singkatnya, Dalam JavaScript, kata kunci ini mengacu pada suatu objek. Objek mana yang bergantung pada bagaimana ini dipanggil (digunakan atau dipanggil). Dengan kata lain, this mereferensikan objek yang sedang memanggil fungsi.

misalkan Anda memiliki objek bernama ‘penghitung’ yang memiliki satu metode bernama next() , saat Anda mengakses metode next() , ia mengembalikan nilai berikutnya dari nilai saat ini menggunakan objek this .

let counter = {   
count: 0,
next: function () {
return ++this.count;
},
};

Di dalam metode next(), kata kunci ini mereferensikan objek hitungan. Cara kerjanya adalah dengan mendapatkan nilai objek hitungan saat ini menggunakan this , dan mengembalikan nilai berikutnya. Dan lihat kode berikut untuk memanggil metode tersebut:

counter.next()

Untuk contoh lebih lanjut, lihat kode di bawah ini:

const test = {
prop: 42,
func: function() {
return this.prop;
},
};

Menurut Anda apa yang akan dikembalikan kode jika saya memanggil metode func?

Bagi yang menjawab 42, Anda benar. Karena metode func mengembalikan nilai objek prop dan dengan itu, Anda mendapatkan 42 sebagai hasilnya.

Sekarang Anda mungkin bertanya, “lalu mengapa saya harus membuat metode baru hanya untuk memanggil objek, mengapa tidak memanggil objek itu sendiri saja?”

Nah, dalam pemrograman ada istilah yang menjelaskan bahwa kita hanya bisa membuat sesuatu sesuai kegunaannya. Mungkin untuk contoh di atas, agak berlebihan untuk menerapkan istilah ini, tetapi untuk kode yang lebih canggih dan kompleks, Anda perlu menerapkan istilah ini.

2 kode di atas adalah contoh penggunaan kata kunci ini dalam sebuah objek.

Global Context

In the global execution context (outside of any function), this refers to the global object.

// In web browsers, the window object is also the global object:
console.log(this === window); // true

a = 37;
console.log(window.a); // 37

this.b = "MDN";
console.log(window.b) // "MDN"
console.log(b) // "MDN"
Function Context

Dalam konteks eksekusi global (di luar fungsi apa pun), ini mengacu pada objek global.

function f1() {
return this;
}

// In a browser:
f1() === window; // true

// In Node:
f1() === globalThis; // true
Class Context

Perilaku ini di kelas dan fungsi serupa, karena kelas adalah fungsi di bawah tenda. Tetapi ada beberapa perbedaan dan peringatan.

Di dalam konstruktor kelas, ini adalah objek biasa. Semua metode non-statis di dalam kelas ditambahkan ke prototipe ini:

class Car {
constructor(name, year) {
this.name = name;
this.year = year;
} age() {
let date = new Date();
return date.getFullYear() - this.year;
}}

Dengan kode di atas, Anda dapat mengakses nama dan tahun saat ini (bergantung pada instance yang dipanggil) dari metode. Dengannya, kita bisa lebih leluasa dalam membuat dan memanggil konstruktor di kelas karena dengan ini membuat penulisan lebih mudah dipahami dan tidak membingungkan.

In this guide, you'll learn about the basic components needed to create and use a packaged JavaScript action. To focus this guide on the components needed to package the action, the functionality of the action's code is minimal. The action prints "Hello World" in the logs or "Hello [who-to-greet]" if you provide a custom name.

This guide uses the GitHub Actions Toolkit Node.js module to speed up development. For more information, see the actions/toolkit repository.

Once you complete this project, you should understand how to build your own JavaScript action and test it in a workflow.

To ensure your JavaScript actions are compatible with all GitHub-hosted runners (Ubuntu, Windows, and macOS), the packaged JavaScript code you write should be pure JavaScript and not rely on other binaries. JavaScript actions run directly on the runner and use binaries that already exist in the runner image.

Warning: When creating workflows and actions, you should always consider whether your code might execute untrusted input from possible attackers. Certain contexts should be treated as untrusted input, as an attacker could insert their own malicious content. For more information, see "."

Prerequisites

Before you begin, you'll need to download Node.js and create a public GitHub repository.

  1. Download and install Node.js 16.x, which includes npm.

    https://nodejs.org/en/download/

  2. Create a new public repository on GitHub.com and call it "hello-world-javascript-action". For more information, see "Create a new repository."

  3. Clone your repository to your computer. For more information, see "Cloning a repository."

  4. From your terminal, change directories into your new repository.

  5. From your terminal, initialize the directory with npm to generate a package.json file.

Create a new file named action.yml in the hello-world-javascript-action directory with the following example code. For more information, see "Metadata syntax for GitHub Actions."

This file defines the who-to-greet input and time output. It also tells the action runner how to start running this JavaScript action.

The actions toolkit is a collection of Node.js packages that allow you to quickly build JavaScript actions with more consistency.

The toolkit @actions/core package provides an interface to the workflow commands, input and output variables, exit statuses, and debug messages.

The toolkit also offers a @actions/github package that returns an authenticated Octokit REST client and access to GitHub Actions contexts.

The toolkit offers more than the core and github packages. For more information, see the actions/toolkit repository.

At your terminal, install the actions toolkit core and github packages.

Now you should see a action.yml1 directory with the modules you just installed and a action.yml2 file with the installed module dependencies and the versions of each installed module.

Writing the action code

This action uses the toolkit to get the who-to-greet input variable required in the action's metadata file and prints "Hello [who-to-greet]" in a debug message in the log. Next, the script gets the current time and sets it as an output variable that actions running later in a job can use.

GitHub Actions provide context information about the webhook event, Git refs, workflow, action, and the person who triggered the workflow. To access the context information, you can use the github package. The action you'll write will print the webhook event payload to the log.

Add a new file called action.yml5, with the following code.

If an error is thrown in the above action.yml5 example, action.yml7 uses the actions toolkit @actions/core package to log a message and set a failing exit code. For more information, see "Setting exit codes for actions."

Creating a README

To let people know how to use your action, you can create a README file. A README is most helpful when you plan to share your action publicly, but is also a great way to remind you or your team how to use the action.

In your hello-world-javascript-action directory, create a hello-world-javascript-action0 file that specifies the following information:

  • A detailed description of what the action does.
  • Required input and output arguments.
  • Optional input and output arguments.
  • Secrets the action uses.
  • Environment variables the action uses.
  • An example of how to use your action in a workflow.

Commit, tag, and push your action to GitHub

GitHub downloads each action run in a workflow during runtime and executes it as a complete package of code before you can use workflow commands like hello-world-javascript-action1 to interact with the runner machine. This means you must include any package dependencies required to run the JavaScript code. You'll need to check in the toolkit core and github packages to your action's repository.

From your terminal, commit your action.yml, action.yml5, action.yml1, package.json, action.yml2, and hello-world-javascript-action0 files. If you added a who-to-greet0 file that lists action.yml1, you'll need to remove that line to commit the action.yml1 directory.

It's best practice to also add a version tag for releases of your action. For more information on versioning your action, see "."

Checking in your action.yml1 directory can cause problems. As an alternative, you can use a tool called who-to-greet4 to compile your code and modules into one file used for distribution.

  1. Install who-to-greet5 by running this command in your terminal. who-to-greet6

  2. Compile your action.yml5 file. who-to-greet8

    You'll see a new who-to-greet9 file with your code and the compiled modules. You will also see an accompanying time0 file containing all the licenses of the action.yml1 you are using.

  3. Change the time2 keyword in your action.yml file to use the new who-to-greet9 file. time5

  4. If you already checked in your action.yml1 directory, remove it. time7

  5. From your terminal, commit the updates to your action.yml, who-to-greet9, and action.yml1 files.

Testing out your action in a workflow

Now you're ready to test your action out in a workflow. When an action is in a private repository, the action can only be used in workflows in the same repository. Public actions can be used by workflows in any repository.

Example using a public action

This example demonstrates how your new public action can be run from within an external repository.

Copy the following YAML into a new file at @actions/core1, and update the @actions/core2 line with your username and the name of the public repository you created above. You can also replace the who-to-greet input with your name.

When this workflow is triggered, the runner will download the hello-world-javascript-action action from your public repository and then execute it.

Example using a private action

Copy the workflow code into a @actions/core1 file in your action's repository. You can also replace the who-to-greet input with your name.

.github/workflows/main.yml

From your repository, click the Actions tab, and select the latest workflow run. Under Jobs or in the visualization graph, click A job to say hello. You should see "Hello Mona the Octocat" or the name you used for the who-to-greet input and the timestamp printed in the log.

Cara menggunakan execution context javascript

Template repositories for creating JavaScript actions

GitHub provides template repositories for creating JavaScript and TypeScript actions. You can use these templates to quickly get started with creating a new action that includes tests, linting, and other recommended practices.