Javascript的method方法详解

1. What is a method

Let’s define and call a regular function:

function greet(who) {
  return `Hello, ${who}!`;
}

greet('World'); // => 'Hello, World!'

The function keyword followed by its name, params, and body: function greet(who) {...} makes a regular function definition.

greet('World') is the regular function invocation. The function greet('World') accepts data from the argument.

What if who is a property of an object? To easily access the properties of an object you can attach the function to that object, in other words, create a method.

Let’s make greet() a method on the object world:

const world = {
  who: 'World',

  greet() {    return `Hello, ${this.who}!`;  }}

world.greet(); // => 'Hello, World!'

greet() { ... } is now a method that belongs to the world object. world.greet() is a method invocation.

Inside of the greet() method this points to the object the method belongs to — world. That’s why this.who expression accesses the property who.

Note that this is also named context.

The context is optional

While in the previous example I’ve used this to access the object the method belongs to — JavaScript, however, doesn’t impose a method to use this.

For this reason you can use an object as a namespace of methods:

const namespace = {
  greet(who) {
    return `Hello, ${who}!`;
  },

  farewell(who) {
    return `Good bye, ${who}!`;
  }
}

namespace.greet('World');    // => 'Hello, World!'
namespace.farewell('World'); // => 'Good bye, World!'

namespace is an object that holds 2 methods: namespace.greet() and namespace.farewell().

The methods do not use this, and namespace serves as a holder of alike methods.

2. Object literal method

As seen in the previous chapter, you can define a method directly in an object literal:

const world = {
  who: 'World',

  greet() {    return `Hello, ${this.who}!`;  }};

world.greet(); // => 'Hello, World!'

greet() { .... } is a method defined on an object literal. Such type of definition is named shorthand method definition (available starting ES2015).

There’s also a longer syntax of methods definition:

const world = {
  who: 'World',

  greet: function() {    return `Hello, ${this.who}!`;  }}

world.greet(); // => 'Hello, World!'

greet: function() { ... } is a method definition. Note the additional presence of a colon and function keyword.

Adding methods dynamically

The method is just a function that is stored as a property on the object. That’s why you can add methods dynamically to an object:

const world = {
  who: 'World',

  greet() {
    return `Hello, ${this.who}!`;
  }
};

// A a new property holding a function
world.farewell = function () {
  return `Good bye, ${this.who}!`;
}

world.farewell(); // => 'Good bye, World!'

world object at first doesn’t have a method farewell. It is added dynamically.

The dynamically added method can be invoked as a method without problems: world.farewell().

3. Class method

In JavaScript, the class syntax defines a class that’s going to serve as a template for its instances.

A class can also have methods:

class Greeter {
  constructor(who) {
    this.who = who;
  }

  greet() {    console.log(this === myGreeter); // logs true    return `Hello, ${this.who}!`;  }}

const myGreeter = new Greeter('World');
myGreeter.greet(); // => 'Hello, World!' 

greet() { ... } is a method defined inside a class.

Every time you create an instance of the class using new operator (e.g. myGreeter = new Greeter('World')), methods are available for invocation on the created instance.

myGreeter.greet() is how you invoke the method greet() on the instance. What’s important is that this inside of the method equals the instance itself: this equals myGreeter inside greet() { ... } method.

4. How to invoke a method

4.1 Method invocation

What’s particularly interesting about JavaScript is that defining a method on an object or class is half of the job. To maintain the method the context, you have to make sure to invoke the method as a… method.

Let me show you why it’s important.

Recall the world object having the method greet() upon it. Let’s check what value has this when greet() is invoked as a method and as a regular function:

const world = {
  who: 'World',

  greet() {
    console.log(this === world);    return `Hello, ${this.who}!`;
  }
};

// Method invocation
world.greet(); // logs true
const greetFunc = world.greet;
// Regular function invocation
greetFunc(); // => logs false

world.greet() is a method invocation. The object world, followed by a dot ., and finally the method itself — that’s what makes the method invocation.

greetFunc is the same function as world.greet. But when invoked as regular function greetFunc()this inside greet() isn’t equal to the world object, but rather to the global object (in a browser this is window).

I name expressions like greetFunc = world.greet separating a method from its object. When later invoking the separated method greetFunc() would make this equal to the global object.

Separating a method from its object can take different forms:

// Method is separated! this is lost!
const myMethodFunc = myObject.myMethod;

// Method is separated! this is lost!
setTimeout(myObject.myMethod, 1000);

// Method is separated! this is lost!
myButton.addEventListener('click', myObject.myMethod)

// Method is separated! this is lost!
<button onClick={myObject.myMethod}>My React Button</button>

To avoid loosing the context of the method, make sure to use the method invocation world.greet() or bind the method manually to the object greetFunc = world.greet.bind(this).

4.2 Indirect function invocation

As stated in the previous section, a regular function invocation has this resolved as the global object. Is there a way for a regular function to have a customizable value of this?

Welcome the indirect function invocation, which can be performed using:

myFunc.call(thisArg, arg1, arg2, ..., argN);
myFunc.apply(thisArg, [arg1, arg2, ..., argN]);

methods available on the function object.

The first argument of myFunc.call(thisArg) and myFunc.apply(thisArg) is the context (the value of this) of the indirect invocation. In other words, you can manually indicate what value this is going to have inside the function.

For example, let’s define greet() as a regular function, and an object aliens having a who property:

function greet() {
  return `Hello, ${this.who}!`;
}

const aliens = {
  who: 'Aliens'
};

greet.call(aliens); // => 'Hello, Aliens!'
greet.apply(aliens); // => 'Hello, Aliens!'

greet.call(aliens) and greet.apply(aliens) are both indirect method invocations. this value inside the greet() function equals aliens object.

The indirect invocation lets you emulate the method invocation on an object!

4.3 Bound function invocation

Finally, here’s the third way how you can make a function be invoked as a method on an object. Specifically, you can bound a function to have a specific context.

You can create a bound function using a special method:

const myBoundFunc = myFunc.bind(thisArg, arg1, arg2, ..., argN);

The first argument of myFunc.bind(thisArg) is the context to which the function is going to be bound to.

For example, let’s reuse the greet() and bind it to aliens context:

function greet() {
  return `Hello, ${this.who}!`;
}

const aliens = {
  who: 'Aliens'
};

const greetAliens = greet.bind(aliens);

greetAliens(); // => 'Hello, Aliens!'

Calling greet.bind(aliens) creates a new function where this is bound to aliens object.

Later, when invoking the bound function greetAliens()this equals aliens inside that function.

Again, using a bound function you can emulate the method invocation.

5. Arrow functions as methods

Using an arrow function as a method isn’t recommended, and here’s why.

Let’s define the greet() method as an arrow function:

const world = {
  who: 'World',

  greet: () => {
    return `Hello, ${this.who}!`;
  }
};

world.greet(); // => 'Hello, undefined!'

Unfortunately, world.greet() returns 'Hello, undefined!' instead of the expected 'Hello, World!'.

The problem is that the value this inside of the arrow function equals this of the outer scope. Always. But what you want is this to equal world object.

That’s why this inside of the arrow function equals the global object: window in a browser. 'Hello, ${this.who}!' evaluates as Hello, ${windows.who}!, which in the end is 'Hello, undefined!'.

I like the arrow functions. But they don’t work as methods.

6. Summary

The method is a function belonging to an object. The context of a method (this value) equals the object the method belongs to.

You can also define methods on classes. this inside of a method of a class equals to the instance.

What’s specific to JavaScript is that it is not enough to define a method. You also need to make sure to use a method invocation. Typically, the method invocation has the following syntax:

// Method invocation
myObject.myMethod('Arg 1', 'Arg 2');

Interestingly is that in JavaScript you can define a regular function, not belonging to an object, but then invoke that function as a method on an arbitrar object. You can do so using an indirect function invocation or bind a function to a particular context:

// Indirect function invocation
myRegularFunc.call(myObject, 'Arg 1', 'Arg 2');
myRegularFunc.apply(myObject, 'Arg 1', 'Arg 2');

// Bound function
const myBoundFunc = myRegularFunc.bind(myObject);
myBoundFunc('Arg 1', 'Arg 2');

Indirect invocation and bounding emulate the method invocation.

To read about all ways you can define functions in JavaScript follow my post 6 Ways to Declare JavaScript Functions.

Confused about how this works in JavaScript? Then I recommend reading my extensive guide Gentle Explanation of “this” in JavaScript .

Quizzzzz: can a method in JavaScript be an asynchronous function?

Html怎样设置点击按钮进行下载

实现点击按钮进行文件下载我们要用到Html5的download标签或者js的自定义函数。

方法一:利用html5的download标签

download标签通利用a标签来储存需要下载的文件的位置,在download的value里面可以设置文件的名称,如果没有设置,a标签就会利用原始的文件。

用法:
<a download="filename">
filename就是你需要下载的文件的名称。
示例:
<!DOCTYPE html> 
<html> 
   <body> 
      <style> 
         p { 
         color: green; 
         } 
      </style> 
      <p>How to trigger a file download when  
         clicking an HTML button or JavaScript? 
      <p> 
         <!-- GFG is the name of the  
            file to be downloaded-->
         <!-- In order to run the code,  
            the location of the file  
            "geeksforgeeks.png" needs to  
            be changed to your local directory, 
            both the HTML and downloadable file  
            needs to be present in the same directory -->
         <a href="geeksforgeeks.png" download="GFG"> 
         <button type="button">Download</button> 
         </a> 
   </body> 
</html> 

方法二:利用js的自定义函数

  • 首先创建一个文本区域(textarea),所有的文本输入都将被发出。
  • 利用createElement属性创建a标签然后分配他的download和href属性。
  • encodeURIComponent将对所有具有特殊含义的内容进行编码,因此您可以将其用于uri的组件。

例如,如果我们有类似“Hello:Geek”的文本?“”中有特殊字符,因此encodeURIComponent将对它们进行编码并附加它以供进一步使用。

  • data:text/plain; charset=utf-8 是href的属性值(如href=“”),它指定该值必须是文本类型,并且具有utf-8类型编码。click()方法模拟鼠标单击元素。
  • 之后,我们只需使用来自textarea的文本和我们的文件名调用下载函数”GFG.txt文件“作为id为’btn’的输入按钮上的参数。
示例:
<!DOCTYPE html> 
<html> 
   <body> 
      <style> 
         p { 
         color: green; 
         } 
      </style> 
      <p> 
          How to trigger a file download when 
          clicking an HTML button or JavaScript? 
      <p> 
         <textarea id="text"> 
             Welcome to GeeksforGeeks 
         </textarea> 
         <br/> 
         <input type="button" id="btn" 
                value="Download" /> 
         <script> 
            function download(file, text) { 
              
                //creating an invisible element 
                var element = document.createElement('a'); 
                element.setAttribute('href',  
                'data:text/plain;charset=utf-8, ' 
                + encodeURIComponent(text)); 
                element.setAttribute('download', file); 
              
                // Above code is equivalent to 
                // <a href="path of file" download="file name"> 
              
                document.body.appendChild(element); 
              
                //onClick property 
                element.click(); 
              
                document.body.removeChild(element); 
            } 
              
            // Start file download. 
            document.getElementById("btn") 
            .addEventListener("click", function() { 
                // Generate download of hello.txt  
                // file with some content 
                var text = document.getElementById("text").value; 
                var filename = "GFG.txt"; 
              
                download(filename, text); 
            }, false); 
         </script> 
   </body> 
</html> 

wordpress的rest api笔记-$.getJSON(url,x )

wordpress 的rest api 需要wp设置长链接才可以,  不能设置 ?P=2 这种链接,需要是localhost/postname这种链接;

$.getJSON(url,x ) 有两个参数,第一个是响应的网站链接,第二个是执行的callback函数;如: getResults() {  $.getJSON(‘http://milad.com.cn/wp-json/wp/v2/posts?search=things’,function(posts) {   alert(posts[0].title.rendered);  });  this.isSpinnerVisable = false; }

Clear time out and set time out

clearTimeour() 函数清除settimeout函数的时间;

settimeout() 函数, setTimeout( ) 是属于 window 的 method, 但我们都是略去 window 这顶层物件名称, 这是用来设定一个时间, 时间到了, 就会执行一个指定的 method;   

第一个参数是要执行的函数,第二个参数是要等多少秒才会执行这个函数;  单位是millisecond  毫秒, 1/1000 秒。 

https://blog.csdn.net/qq_28256783/article/details/80097092 ; 

js 键盘代码的操作方法,要注意e的传递方式$(document).on(“keyup”,this.keyDispatcher.bind(this)); }

 //3 methods (functions,actions .. ) keyDispatcher(e) {  console.log(e.keyCode); }

如果keycode代码是 83 打开搜索的写法是: if (e.keyCode == 83) {
   this.openOverlay();  }openOverlay() {  this.searchOverlay.addClass(“search-overlay–active”);  $(“body”).addClass(“body-no-scroll”); }

Js without Jquery make the search.js from udemy course

用Javascript dom实现rest api search的操作:


import axios from "axios"

class Search {
  // 1. describe and create/initiate our object
  constructor() {
    this.addSearchHTML()
    this.resultsDiv = document.querySelector("#search-overlay__results")
    this.openButton = document.querySelectorAll(".js-search-trigger")
    this.closeButton = document.querySelector(".search-overlay__close")
    this.searchOverlay = document.querySelector(".search-overlay")
    this.searchField = document.querySelector("#search-term")
    this.isOverlayOpen = false
    this.isSpinnerVisible = false
    this.previousValue
    this.typingTimer
    this.events()
  }

  // 2. events
  events() {
    this.openButton.forEach(el => {
      el.addEventListener("click", e => {
        e.preventDefault()
        this.openOverlay()
      })
    })

    this.closeButton.addEventListener("click", () => this.closeOverlay())
    document.addEventListener("keydown", e => this.keyPressDispatcher(e))
    this.searchField.addEventListener("keyup", () => this.typingLogic())
  }

  // 3. methods (function, action...)
  typingLogic() {
    if (this.searchField.value != this.previousValue) {
      clearTimeout(this.typingTimer)

      if (this.searchField.value) {
        if (!this.isSpinnerVisible) {
          this.resultsDiv.innerHTML = '<div class="spinner-loader"></div>'
          this.isSpinnerVisible = true
        }
        this.typingTimer = setTimeout(this.getResults.bind(this), 750)
      } else {
        this.resultsDiv.innerHTML = ""
        this.isSpinnerVisible = false
      }
    }

    this.previousValue = this.searchField.value
  }

  async getResults() {
    try {
      const response = await axios.get(universityData.root_url + "/wp-json/university/v1/search?term=" + this.searchField.value)
      const results = response.data
      this.resultsDiv.innerHTML = `
        <div class="row">
          <div class="one-third">
            <h2 class="search-overlay__section-title">General Information</h2>
            ${results.generalInfo.length ? '<ul class="link-list min-list">' : "<p>No general information matches that search.</p>"}
              ${results.generalInfo.map(item => `<li><a href="${item.permalink}">${item.title}</a> ${item.postType == "post" ? `by ${item.authorName}` : ""}</li>`).join("")}
            ${results.generalInfo.length ? "</ul>" : ""}
          </div>
          <div class="one-third">
            <h2 class="search-overlay__section-title">Programs</h2>
            ${results.programs.length ? '<ul class="link-list min-list">' : `<p>No programs match that search. <a href="${universityData.root_url}/programs">View all programs</a></p>`}
              ${results.programs.map(item => `<li><a href="${item.permalink}">${item.title}</a></li>`).join("")}
            ${results.programs.length ? "</ul>" : ""}

            <h2 class="search-overlay__section-title">Professors</h2>
            ${results.professors.length ? '<ul class="professor-cards">' : `<p>No professors match that search.</p>`}
              ${results.professors
          .map(
            item => `
                <li class="professor-card__list-item">
                  <a class="professor-card" href="${item.permalink}">
                    <img class="professor-card__image" src="${item.image}">
                    <span class="professor-card__name">${item.title}</span>
                  </a>
                </li>
              `
          )
          .join("")}
            ${results.professors.length ? "</ul>" : ""}

          </div>
          <div class="one-third">
            <h2 class="search-overlay__section-title">Campuses</h2>
            ${results.campuses.length ? '<ul class="link-list min-list">' : `<p>No campuses match that search. <a href="${universityData.root_url}/campuses">View all campuses</a></p>`}
              ${results.campuses.map(item => `<li><a href="${item.permalink}">${item.title}</a></li>`).join("")}
            ${results.campuses.length ? "</ul>" : ""}

            <h2 class="search-overlay__section-title">Events</h2>
            ${results.events.length ? "" : `<p>No events match that search. <a href="${universityData.root_url}/events">View all events</a></p>`}
              ${results.events
          .map(
            item => `
                <div class="event-summary">
                  <a class="event-summary__date t-center" href="${item.permalink}">
                    <span class="event-summary__month">${item.month}</span>
                    <span class="event-summary__day">${item.day}</span>  
                  </a>
                  <div class="event-summary__content">
                    <h5 class="event-summary__title headline headline--tiny"><a href="${item.permalink}">${item.title}</a></h5>
                    <p>${item.description} <a href="${item.permalink}" class="nu gray">Learn more</a></p>
                  </div>
                </div>
              `
          )
          .join("")}

          </div>
        </div>
      `
      this.isSpinnerVisible = false
    } catch (e) {
      console.log(e)
    }
  }

  keyPressDispatcher(e) {
    if (e.keyCode == 83 && !this.isOverlayOpen && document.activeElement.tagName != "INPUT" && document.activeElement.tagName != "TEXTAREA") {
      this.openOverlay()
    }

    if (e.keyCode == 27 && this.isOverlayOpen) {
      this.closeOverlay()
    }
  }

  openOverlay() {
    this.searchOverlay.classList.add("search-overlay--active")
    document.body.classList.add("body-no-scroll")
    this.searchField.value = ""
    setTimeout(() => this.searchField.focus(), 301)
    console.log("our open method just ran!")
    this.isOverlayOpen = true
    return false
  }

  closeOverlay() {
    this.searchOverlay.classList.remove("search-overlay--active")
    document.body.classList.remove("body-no-scroll")
    console.log("our close method just ran!")
    this.isOverlayOpen = false
  }

  addSearchHTML() {
    document.body.insertAdjacentHTML(
      "beforeend",
      `
      <div class="search-overlay">
        <div class="search-overlay__top">
          <div class="container">
            <i class="fa fa-search search-overlay__icon" aria-hidden="true"></i>
            <input type="text" class="search-term" placeholder="What are you looking for?" id="search-term">
            <i class="fa fa-window-close search-overlay__close" aria-hidden="true"></i>
          </div>
        </div>
        
        <div class="container">
          <div id="search-overlay__results"></div>
        </div>

      </div>
    `
    )
  }
}

export default Search