javascript 方法与函数,以及其他问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15285293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method vs Functions, and other questions
提问by Karan Goel
With respect to JS, what's the difference between the two? I know methods are associated with objects, but am confused what's the purpose of functions? How does the syntax of each of them differ?
关于JS,两者有什么区别?我知道方法与对象相关联,但我很困惑函数的目的是什么?它们各自的语法有何不同?
Also, what's the difference between these 2 syntax'es:
另外,这两种语法有什么区别:
var myFirstFunc = function(param) {
//Do something
};
and
和
function myFirstFunc(param) {
//Do something
};
Also, I saw somewhere that we need to do something like this before using a function:
另外,我在某处看到我们需要在使用函数之前做这样的事情:
obj.myFirstFunc = myFirstFunc;
obj.myFirstFunc("param");
Why is the first line required, and what does it do?
为什么需要第一行,它有什么作用?
Sorry if these are basic questions, but I'm starting with JS and am confused.
对不起,如果这些是基本问题,但我从 JS 开始并且感到困惑。
EDIT: For the last bit of code, this is what I'm talking about:
编辑:对于最后一点代码,这就是我要说的:
// 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;
// and down here we just use the method we already made
bob.setAge = setAge;
回答by mastaBlasta
To answer your title question as to what is the difference between a 'function' and a 'method'.
回答关于“函数”和“方法”之间有什么区别的标题问题。
It's semantics and has to do with what you are trying to express.
这是语义,与您要表达的内容有关。
In JavaScript every function is an object. An object is a collection of key:value pairs. If a value is a primitive (number, string, boolean), or another object, the value is considered a property. If a value is a function, it is called a 'method'.
在 JavaScript 中,每个函数都是一个对象。对象是键值对的集合。如果值是原始值(数字、字符串、布尔值)或另一个对象,则该值被视为属性。如果值是函数,则称为“方法”。
Within the scope of an object, a function is referred to as a method of that object. It is invoked from the object namespace MyObj.theMethod().
Since we said that a function is an object, a function within a function can be considered a method of that function.
在对象的范围内,函数被称为该对象的方法。它是从对象命名空间调用的,MyObj.theMethod().
既然我们说函数是一个对象,那么函数内的函数可以被认为是该函数的方法。
You could say things like “I am going to use the save methodof my object.” And "This save method accepts a functionas a parameter.” But you generally wouldn't say that a function accepts a method as a parameter.
你可以这样说:“我将使用我的对象的 save方法。” 并且“这个保存方法接受一个函数作为参数。” 但是你通常不会说一个函数接受一个方法作为参数。
Btw, the book JavaScript Patternsby Stoyan Stefanovcovers your questions in detail, and I highly recommend it if you really want to understand the language. Here's a quote from the book on this subject:
顺便说一句,这本书的JavaScript模式由斯托扬斯特凡包括您详细的问题,我强烈建议,如果你真的想了解的语言。这是书中关于这个主题的引述:
So it could happen that a function A, being an object, has properties and methods, one of which happens to be another function B. Then B can accept a function C as an argument and, when executed, can return another function D.
因此,作为对象的函数 A 可能具有属性和方法,其中一个恰好是另一个函数 B。然后 B 可以接受函数 C 作为参数,并且在执行时可以返回另一个函数 D。
回答by Pushpendra Singh
There is a slight difference -
有一点区别——
Method : Method is a function when object is associated with it.
方法:当对象与其关联时,方法是一个函数。
var obj = {
name : "John snow",
work : function someFun(paramA, paramB) {
// some code..
}
Function : When no object is associated with it , it comes to function.
功能:当没有对象与之关联时,它就涉及功能。
function fun(param1, param2){
// some code...
}
回答by Oliver Sieweke
Many answers are saying something along the lines that a methodis what a function is called when it is defined on an object.
许多答案都在说,方法就是在对象上定义时调用的函数。
While this is often true in the way the word is used when people talk about JavaScript or object oriented programming in general (see here), it is worth noting that in ES6 the term methodhas taken on a very specific meaning(see section 14.3 Method Definitionsof the specs).
虽然当人们谈论 JavaScript 或一般的面向对象编程时,这个词的使用方式通常是这样的(参见这里),但值得注意的是,在 ES6 中,术语方法具有非常具体的含义(参见第14.3节方法规范的定义)。
Method Definitions
方法定义
A method(in the strict sense) is a function that was defined through the concise method syntax in an object literal or as a class method in a class declaration / expression:
阿法(严格意义上的)是通过在对象文本或作为在类声明/表达的一类方法的简明方法的语法定义的函数:
// In object literals:
const obj = {
method() {}
};
// In class declarations:
class MyClass {
method() {}
}
Method Specificities
方法特性
This answergives a good overview about the specificities of methods(in the strict sense), namely:
这个答案很好地概述了方法的特殊性(严格意义上),即:
- methods get assigned an internal
[[HomeObject]]
property which allows them to usesuper
. - methods are not created with a
prototype
property and they don't have an internal[[Construct]]
method which means that they cannot be called withnew
. - the name of a method does not become a binding in the method's scope.
- 方法被分配了一个内部
[[HomeObject]]
属性,允许它们使用super
. - 方法不是用
prototype
属性创建的,也没有内部[[Construct]]
方法,这意味着它们不能用new
. - 方法的名称不会成为方法范围内的绑定。
Below are some examples illustrating how methods (in the strict sense) differ from functions defined on objects through function expressions:
下面是一些示例,说明方法(严格意义上的)与通过函数表达式定义在对象上的函数有何不同:
Example 1
示例 1
const obj = {
method() {
super.test; // All good!
},
ordinaryFunction: function ordinaryFunction() {
super.test; // SyntaxError: 'super' keyword unexpected here
}
};
Example 2
示例 2
const obj = {
method() {},
ordinaryFunction: function ordinaryFunction() {}
};
console.log( obj.ordinaryFunction.hasOwnProperty( 'prototype' ) ); // true
console.log( obj.method.hasOwnProperty( 'prototype' ) ); // false
new obj.ordinaryFunction(); // All good !
new obj.method(); // TypeError: obj.method is not a constructor
Example 3
示例 3
const obj = {
method() {
console.log( method );
},
ordinaryFunction: function ordinaryFunction() {
console.log( ordinaryFunction );
}
};
obj.ordinaryFunction() // All good!
obj.method() // ReferenceError: method is not defined
回答by Ryan
Your first line, is creating an object that references a function. You would reference it like this:
您的第一行是创建一个引用函数的对象。你会像这样引用它:
myFirstFunc(param);
But you can pass it to another function since it will return the function like so:
但是你可以将它传递给另一个函数,因为它会像这样返回函数:
function mySecondFunction(func_param){}
mySecondFunction(myFirstFunc);
The second line just creates a function called myFirstFunc
which would be referenced like this:
第二行只是创建了一个被调用的函数myFirstFunc
,它会像这样被引用:
myFirstFunc(param);
And is limited in scope depending on where it is declared, if it is declared outside of any other function it belongs to the global scope. However you can declare a function inside another function. The scope of that function is then limited to the function its declared inside of.
并且根据声明的位置限制范围,如果它在任何其他函数之外声明,则它属于全局范围。但是,您可以在另一个函数中声明一个函数。然后该函数的作用域被限制在其内部声明的函数内。
function functionOne(){
function functionTwo(){}; //only accessed via the functionOne scope!
}
Your final examples are creating instances of functions that are then referenced though an object parameter. So this:
您的最后一个示例是创建函数的实例,然后通过对象参数引用这些实例。所以这:
function myFirstFunc(param){};
obj.myFirst = myFirstFunc(); //not right!
obj.myFirst = new myFirstFunc(); //right!
obj.myFirst('something here'); //now calling the function
Says that you have an object that references an instance of a function. The key here is that if the function changes the referenceyou stored in obj.myFirst
will not be changed.
说你有一个引用函数实例的对象。这里的关键是如果函数改变了你存储的引用obj.myFirst
不会改变。
While @kevin is basically right there is only functions in JS you can create functions that are much more like methods then functions, take this for example:
虽然@kevin 基本上是对的,但 JS 中只有函数,您可以创建更像方法而不是函数的函数,例如:
function player(){
this.stats = {
health: 0,
mana: 0,
get : function(){
return this;
},
set : function( stats ){
this.health = stats.health;
this.mana = stats.mana;
}
}
You could then call player.stats.get()
and it would return to you the value of heath
, and mana
. So I would consider get
and set
in this instance to be methods of the player.stats
object.
然后你可以调用player.stats.get()
它,它会返回给你heath
, 和的值mana
。所以我会考虑get
并且set
在这种情况下是player.stats
对象的方法。
回答by Ridha Rezzag
A method is a property of an object whose value is a function. Methods are called on objects in the following format: object.method().
方法是对象的属性,其值为函数。以下列格式在对象上调用方法:object.method()。
//this is an object named developer
//这是一个名为developer的对象
const developer = {
name: 'Andrew',
sayHello: function () {
console.log('Hi there!');
},
favoriteLanguage: function (language) {
console.log(`My favorite programming language is ${language}`);
}
};
// favoriteLanguage: and sayHello: and name: all of them are proprieties in the object named developer
// favoriteLanguage: 和 sayHello: 和 name: 它们都是名为 developer 的对象中的属性
now lets say you needed to call favoriteLanguage propriety witch is a function inside the object..
现在假设您需要调用最喜爱的语言属性女巫是对象内的一个函数..
you call it this way
你这样称呼它
developer.favoriteLanguage('JavaScript');
// My favorite programming language is JavaScript'
so what we name this: developer.favoriteLanguage('JavaScript'); its not a function its not an object? what it is? its a method
所以我们把它命名为: developer.favoriteLanguage('JavaScript'); 它不是一个函数它不是一个对象?这是什么?它的一种方法
回答by mustafa kemal tuna
4.3.31method : function that is the value of a property
NOTE When a function is called as a method of an object, the object is passed to the function as its this value.
4.3.31method : 作为属性值的函数
注意当一个函数作为一个对象的方法被调用时,该对象作为它的 this 值传递给函数。
It is very clear: when you call a function if it implicitly has a this
(to point an object) and if you can't call the function without an object, the functiondeserves to name as method.
很清楚:当你调用一个函数时,如果它隐含地有一个this
(指向一个对象),并且如果你不能在没有对象的情况下调用该函数,则该函数应该命名为method。
回答by ticktock
A function executes a list of statements example:
一个函数执行一系列语句示例:
function add() {
var a = 2;
var b = 3;
var c = a + b;
return c;
}
1) A method is a function that is applied to an object example:
1) 方法是应用于对象示例的函数:
var message = "Hello world!";
var x = message.toUpperCase(); // .toUpperCase() is a built in function
2) Creating a method using an object constructor. Once the method belongs to the object you can apply it to that object. example:
2) 使用对象构造函数创建方法。一旦该方法属于该对象,您就可以将其应用于该对象。例子:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.name = function() {return this.firstName + " " + this.lastName;};
}
document.getElementById("demo").innerHTML = person.fullName(); // using the
method
Definition of a method: A method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object.
方法的定义:方法是作为函数的对象的属性。方法的定义方式与普通函数的定义方式相同,不同之处在于它们必须被分配为对象的属性。
回答by Dave
var myFirstFunc = function(param) {
//Do something
};
and
和
function myFirstFunc(param) {
//Do something
};
are (almost) identical. The second is (usually) just shorthand. However, as this jsfiddle (http://jsfiddle.net/cu2Sy/) shows, function myFirstFunc
will cause the function to be defined as soon as the enclosing scope is entered, whereas myFirstFunc = function
will only create it once execution reaches that line.
是(几乎)相同的。第二个(通常)只是速记。然而,正如这个 jsfiddle ( http://jsfiddle.net/cu2Sy/) 所示,function myFirstFunc
一旦进入封闭范围,就会导致函数被定义,而myFirstFunc = function
只有在执行到达该行时才会创建它。
As for methods, they have a this
argument, which is the current object, so:
至于方法,它们有一个this
参数,即当前对象,因此:
var obj = {};
obj.func = function( ) {
// here, "this" is obj
this.test = 2;
}
console.log( obj.test ); // undefined
obj.func( );
console.log( obj.test ); // 2
The exact syntax you showed is because you can also do this:
您显示的确切语法是因为您也可以这样做:
function abc( ) {
this.test = 2;
}
var obj = {};
obj.func = abc;
obj.func( ); // sets obj.test to 2
but you shouldn't without good reason.
但你不应该没有充分的理由。