简体   繁体   English

方法和函数有什么区别? 如何声明方法?

[英]What is the difference between Methods and Functions? How to declare a method?

I am learning Javascript on Codecademy. 我正在Codecademy上学习Javascript。 As my understanding Method is a function associated with the objects. 据我了解,Method是与对象关联的功能。 I think to call it a method it should inside an object. 我认为将其称为应在对象内部的方法。 Is it? 是吗? Should I really fully understand main difference between functions and methods to write error free code. 我是否应该真正完全理解编写无错误代码的函数和方法之间的主要区别。 This is very confusing to me. 这让我很困惑。

Below it the Codecademy code, they say on line 2 'setAge' is a Method where it is clearly looks like a function. 在其下方的Codecademy代码中,他们说在第2行“ setAge”是一个方法,在其中它显然看起来像一个函数。 It is not even related to any Object yet. 它甚至与任何对象都不相关。 Coz it is not even inside of any object. 因为它甚至不在任何对象内部。

// here we define our method using "this", before we even introduce bob
var setAge = function (newAge) {
  this.age = newAge;
};

// now we make bob
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;

// make susan here, and first give her an age of 25
var susan = new Object();
susan.age = 25;
susan.setAge = setAge;
susan.setAge(35);
// here, update Susan's age to 35 using the method

That's a good question, I could see how that could be confusing. 这是一个很好的问题,我可以看到这可能会造成混淆。 It appears that they are referring to it as a method because they later modify the bob object to include the function, thereby making it a "method". 看来他们将其称为方法是因为他们后来修改了bob对象以包括该功能,从而使其成为“方法”。

var setAge = function (newAge) {
  // using "this" sometimes indicates
  // that a function may instead be an object method
  this.age = newAge;
};

// becomes a method
bob.setAge = setAge;

Their code is equivalent to the following: 它们的代码等效于以下内容:

bob.setAge = function (newAge) {
  this.age = newAge;
};

You are right in your understanding about methods. 您对方法的理解是正确的。

As others have said, a method and a function have a lot in common, in fact all methods are functions. 正如其他人所说,方法和函数有很多共同点,实际上所有方法都是函数。

The biggest difference is that a method is attached to an object and the this value gets set when that object is called. 最大的区别是方法附加到对象,并且在调用该对象时会设置this值。

I've made a snippet to demonstrate 我做了一个片段来演示

 "use strict"; var bob = { bool: true }; bob.test = function() { console.log("this = ", this); }; console.log("Here is bob test and 'this'"); bob.test(); // Separate the method var tmp = bob.test; // In strict mode, this will be undefined. // In non-strict, it will be the same as `window` tmp(); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM