javascript:函数和对象...?

发布于 2024-11-06 07:50:42 字数 329 浏览 0 评论 0原文

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

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

并且:

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

我的问题:

  1. 您可以为函数调用 new 吗,就像为对象调用一样吗?
  2. “this”的使用成为可能,因为我们使用该函数作为对象?

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 new for a function, as for an object?
  2. The use of "this" is made possible, because we use that function as an object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

他夏了夏天 2024-11-13 07:50:43

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

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

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

如果你有这个,那么你就这样做:

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

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

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

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

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.

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

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:

var Tip = { content: txt, show: false };
var tipObj = new Tip();
〆凄凉。 2024-11-13 07:50:43

我花了近 8 年的时间(2008-2016)来努力理解这些概念(函数作为对象、原型对象、__proto__ 属性、构造函数属性)。首先,在多次阅读第 6、8、9 章后,我开始了 David Flanagan 的《JavaScript Definitive Guide 5/6th ed》4-5 年;它对我来说没有任何意义,但在互联网上挣扎之后,我知道能够将函数(具有属性的典型 C++ 函数)作为对象进行管理;因为对象也可以有方法。幸运的是,在 2015 年的第七年,我开始了 Wrox Nicholas C. Zakas“Web 开发人员的专业 JavaScript 第 3 版”第 6,7 章;理解以上四个概念确实非常有帮助。传统上,在 C/C++/C# 中,函数被认为是修改对象;或者换句话说,它们是为了“做某事”而创建的,而对象是为了通过更改其自身对象状态的方法来维护全局运行上下文的状态。那么,如果函数可以是第一类对象,那么为什么对象不能像函数一样呢?

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

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

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 ?

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.

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

甜味拾荒者 2024-11-13 07:50:43

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

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

对于#2:“this”根据调用模式而不同(由 Douglas Crockford 术语)。 Crockford 说有 4 种模式(方法模式、函数模式、构造函数模式和“应用”模式)

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

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 )

可可 2024-11-13 07:50:43

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

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

并使用以下命令获取一个新实例: var myTip = new Tip("my Epidemic Tip");
这类似于 c#:

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

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

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#:

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) this is referring to the current instance of the class.

你爱我像她 2024-11-13 07:50:43
  1. 事实上,数组、函数等所有数据类型都是对象。
  2. 当我们将函数作为类声明时,这是有效的。
  1. In fact, every data types like array, functions are Objects.
  2. When we take function as a class declaration, this works.
迷迭香的记忆 2024-11-13 07:50:42

您正在寻找构造函数概念。

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}

但是,为了创建特定类型的新对象(也就是说,继承原型、具有构造函数等),函数可以引用 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
}

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

因此:

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}

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

 // 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"

按照惯例,像 make_person_object 这样的构造函数都是大写、单数和“名词”(因为缺乏更好的术语)——因此我们可以有一个 Person 构造函数,而不是一个 make_person_object ,后者可能会被误认为是普通函数。

另请参阅:

You are looking for the constructor concept.

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

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 this and if it is called with the new operator then it will return an object with all of the attributes that are defined on this in the function - this in such cases references the new object we are creating.

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_person and make_person_object is 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 new operator however, will define your this attributes on the current this object (generally window if you are operating in the browser.)

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 prototype property of make_person_object on each "Person" we create. This enables us to add methods and attributes to persons after the fact:

 // 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_object are capitalized, singularized and "nouned" (for lack of a better term) -- thus we would have a Person constructor, rather than a make_person_object which might be mistaken for an ordinary function.

See also:

安穩 2024-11-13 07:50:42

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

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

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文