javascript:函数和对象...?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5958417/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:40:23  来源:igfitidea点击:

javascript : function and object...?

javascriptfunctionobject

提问by Paul

Can you call a function as an object? For example:

您可以将函数作为对象调用吗?例如:

function Tip(txt){      
    this.content = txt;  
    this.shown = false;  
}

And:

和:

var tip = new Tip(elem.attr('title'));

My questions:

我的问题:

  1. Can you call newfor a function, as for an object?
  2. The use of "this" is made possible, because we usethat function as an object?
  1. 你能调用new一个函数,比如一个对象吗?
  2. 使“this”的使用成为可能,因为我们那个函数用作对象?

回答by Sean Vieira

You are looking for the constructorconcept.

你正在寻找这个constructor概念。

All functions in JavaScript are objectsand can be used to create objects:

JavaScript中的所有函数都是对象,可用于创建对象:

function make_person(firstname, lastname, age) {
    person = {};
    person.firstname = firstname;
    person.lastname = lastname;
    person.age = age;
    return person;
}
make_person("Joe", "Smith", 23);
// {firstname: "Joe", lastname: "Smith", age: 23}

However, in order to create new objects of a particular type (that is to say, that inherit a prototype, have a constructor, etc), a function can reference thisand if it is called with the newoperatorthen it will return an object with all of the attributes that are defined on thisin the function - thisin such cases references the new object we are creating.

但是,为了创建特定类型的新对象(也就是说,继承原型,具有构造函数等),函数可以引用this如果使用new运算符调用它,则它将返回一个包含所有对象的对象this在函数中定义的属性-this在这种情况下引用我们正在创建的新对象。

function make_person_object(firstname, lastname, age) {
    this.firstname = firstname;
    this.lastname = lastname;
    this.age = age;
    // Note, we did not include a return statement
}

The key difference to note between make_personand make_person_objectis that calling new make_person()(as opposed to simply make_person()) will not do anything different ... both will produce the same object. Calling make_person_object()without the newoperator however, will define your thisattributes on the current thisobject (generally windowif you are operating in the browser.)

make_person和之间要注意的主要区别make_person_object是调用new make_person()(而不是简单的make_person())不会做任何不同的事情......两者都会产生相同的对象。然而,在make_person_object()没有new操作符的情况下调用将定义this当前this对象的属性(通常window如果您在浏览器中操作。)

Thus:

因此:

var Joe = make_person_object("Joe", "Smith", 23);
console.log(Joe); // undefined
console.log(window.firstname) // "Joe" (oops)

var John = new make_person_object("John", "Smith", 45);
console.log(John); // {firstname: "John", lastname: "Smith", age: 45}

Also, as @RobG points out, this way of doing things creates a reference to the prototypeproperty of make_person_objecton each "Person" we create. This enables us to add methods and attributes to persons after the fact:

此外,正如@RobG 指出的那样,这种做事方式会创建对我们创建的每个“人”的prototype属性的引用make_person_object。这使我们能够在事后为人员添加方法和属性:

 // Assuming all that came before
make_person_object.prototype.full_name = "N/A";
make_person_object.prototype.greet = function(){ 
    console.log("Hello! I'm", this.full_name, "Call me", this.firstname); 
};
John.full_name // "N/A"
John.full_name = "John Smith"; 
make_person_object.full_name // Still "N/A"
John.greet(); // "Hello! I'm John Smith Call me John"

Convention has it that constructor functions like make_person_objectare capitalized, singularized and "nouned" (for lack of a better term) -- thus we would have a Personconstructor, rather than a make_person_objectwhich might be mistaken for an ordinary function.

make_person_object约定俗成的构造函数像大写、单数化和“名词化”(因为没有更好的术语)——因此我们会有一个Person构造函数,而不是一个make_person_object可能被误认为是普通函数的 a 。

See also:

也可以看看:

回答by Adam Bergmark

Every function has a reference to this. if you call Tip(), thiswill refer to the global object. If you call new Tip(), a new object with a reference to Tip.prototype is created and thiswill refer to that new object.

每个函数都有一个对this. 如果调用Tip(),this将引用全局对象。如果调用new Tip(),则会创建一个引用 Tip.prototype 的新对象,this并将引用该新对象。

You can't use newon objects, for instance new {}throws TypeError: object is not a function. If you are refering to new Object()then that works since Objectis a function.

您不能new在对象上使用,例如new {}throws TypeError: object is not a function。如果您指的是new Object()那么有效,因为它Object是一个函数。

回答by Tom Chandler

Yes. In JavaScript, technically everything is an object. When you use new, it creates an instance of the Tip object and then calls the Tip function as if it were a constructor.

是的。在 JavaScript 中,从技术上讲,一切都是对象。当您使用 new 时,它会创建 Tip 对象的一个​​实例,然后像调用构造函数一样调用 Tip 函数。

If you want to add functions to the Tip object, you should add them to Tip's prototype like so:

如果你想向 Tip 对象添加函数,你应该像这样将它们添加到 Tip 的原型中:

Tip.prototype.getContent = function() {
    return this.content;
};

If you have that, and then you do:

如果你有,然后你做:

var tip = new Tip("this  is my content.");
alert(tip.getContent());

It'll show a message saying "this is my content."

它会显示一条消息,说“这是我的内容”。

You can only use new, however, if the object has a functional implementation. So this won't work:

但是,如果对象具有功能实现,则只能使用 new。所以这行不通:

var Tip = { content: txt, show: false };
var tipObj = new Tip();

回答by Saurabh

I have struggled to understand these concepts(functions as objects, prototype objects, __proto__ property, constructor property) for almost 8 years(2008-2016). First I started David Flanagan "JavaScript Definitive Guide 5/6th ed" for 4-5 years after multiple readings of Chapters 6,8,9; it did not make any sense to me but after struggling on Internet I some what able to manage functions(typical C++ function with properties) as objects; because object can also have methods. And luckily in 7th year 2015, I started Wrox Nicholas C. Zakas "Professional JavaScript for Web Developers 3rd ed" Chapter 6,7; and it was really very helpful to understand above four concepts. Traditionally in C/C++/C# functions are thought of as to modify an object; or in other words they are made for the "doing something" where as Objects are made for maintaining state of global running context with methods to change its own object state. So if functions can be first class objects then why objects can not be like functions ?

近 8 年(2008-2016)我一直在努力理解这些概念(作为对象的函数、原型对象、__proto__ 属性、构造函数属性)。首先,在多次阅读第 6、8、9 章后,我开始使用 David Flanagan “JavaScript Definitive Guide 5/6th ed” 4-5 年;这对我来说没有任何意义,但在互联网上挣扎之后,我可以将函数(具有属性的典型 C++ 函数)作为对象进行管理;因为对象也可以有方法。幸运的是,在 2015 年的第 7 年,我开始编写 Wrox Nicholas C. Zakas “Professional JavaScript for Web Developers 3rd ed”第 6,7 章;理解以上四个概念真的很有帮助。传统上,在 C/C++/C# 中,函数被认为是修改对象;或者换句话说,它们是为“做某事”而设计的 其中,对象用于维护全局运行上下文的状态,并使用更改其自身对象状态的方法。那么如果函数可以是一等对象,那么为什么对象不能像函数呢?

The main key question here should be WHY ? Why not single conceptual entity like "associative-function" or "chained-arguments" ? And here is my understanding: Browser exe is a single threaded application and this exe controls calling JS interpreter with predefined scope chain(some what similar to a string of commands with arguments); now at runtime the JS engine(not interpreter) loads the code in hoisting fashion(since there is no main method so uplifting the well defined keyworded codes and its call). In this hoisted code if functions are not treated as objects then they have to be maintained on separate call context(out of scope chain) which is easily possible in c/c++/c#(bcoz of multi thread and unlimited memory) but not in JS. Hence "to-do smth on chained object" makes a java script function as first class object. In fact JS objects also do the same thing; the only difference is "calling an object" is not there in objects where as "calling a function" is chained context which make sense. Functions can also be thought of as "bunch of variables with assembly language instructions with address link(chain)". The linking part is another side of story as top->bottom linking(prototype object) vs bottom->top linking(__proto__ property) vs object blue print->object instances(constructor property). Few months back I found the following image as helpful for understanding linking.

这里的主要关键问题应该是 WHY ?为什么不是像“关联函数”或“链式参数”这样的单一概念实体?这是我的理解:浏览器 exe 是一个单线程应用程序,这个 exe 控制调用具有预定义作用域链的 JS 解释器(有些类似于带有参数的命令字符串);现在在运行时,JS 引擎(不是解释器)以提升方式加载代码(因为没有 main 方法,所以提升了定义良好的关键字代码及其调用)。在这个提升的代码中,如果函数不被视为对象,那么它们必须在单独的调用上下文(范围链外)中维护,这在 c/c++/c#(多线程和无限内存的 bcoz)中很容易实现,但在 JS 中则不然. 因此“对链式对象的待办事项” 使java脚本函数作为第一类对象。事实上 JS 对象也做同样的事情;唯一的区别是“调用对象”不在对象中,而“调用函数”是有意义的链接上下文。函数也可以被认为是“一堆带有地址链接(链)的汇编语言指令的变量”。链接部分是故事的另一面,如顶部->底部链接(原型对象)与底部->顶部链接(__proto__ 属性)与对象蓝图->对象实例(构造函数属性)。几个月前,我发现下图有助于理解链接。函数也可以被认为是“一堆带有地址链接(链)的汇编语言指令的变量”。链接部分是故事的另一面,如顶部->底部链接(原型对象)与底部->顶部链接(__proto__ 属性)与对象蓝图->对象实例(构造函数属性)。几个月前,我发现下图有助于理解链接。函数也可以被认为是“一堆带有地址链接(链)的汇编语言指令的变量”。链接部分是故事的另一面,如顶部->底部链接(原型对象)与底部->顶部链接(__proto__ 属性)与对象蓝图->对象实例(构造函数属性)。几个月前,我发现下图有助于理解链接。

http://judis.me/wordpress/wp-content/uploads/2015/08/JavaScriptDiagram.png"JS Object model"

http://judis.me/wordpress/wp-content/uploads/2015/08/JavaScriptDiagram.png“JS 对象模型”

回答by Thomas Shields

The function is acting as a constructor on a class. Alternatively, you could do:

该函数充当类的构造函数。或者,你可以这样做:

function Tip(txt) {
 return {
 content: txt,
 shown: false
}
}

and get a new instance with: var myTip = new Tip("my epic tip");This is similar to, say, c#:

并获得一个新实例:var myTip = new Tip("my epic tip");这类似于,比如说,c#:

public class Tip {
string text = "";
public Tip(string txt) {
text = txt;
}
}

So, sort of. 1) You're calling new since the function is essentially acting as a class, and 2) thisis referring to the current instance of the class.

所以,有点。1) 您调用 new 是因为该函数本质上是一个类,并且 2)this指的是该类的当前实例。

回答by user670800

for #1 : There is an object called Function (capital F)

对于#1:有一个名为Function(大写F)的对象

var f = new Function("x", "y", "return x*y;");

var f = new Function("x", "y", "return x*y;");

for #2 : the "this" is different depending on innvocation pattern (as termed by Douglas Crockford). Crockford said there are 4 patterns ( method pattern , function pattern , constructor pattern , and "apply" pattern )

#2 :“this”根据调用模式而不同(如 Douglas Crockford 所称)。Crockford 说有 4 种模式(方法模式、函数模式、构造器模式和“应用”模式)

回答by xblymmx

  1. In fact, every data types like array, functions are Objects.
  2. When we take function as a class declaration, this works.
  1. 事实上,像数组、函数这样的所有数据类型都是对象。
  2. 当我们将函数作为类声明时,这是有效的。