java脚本调用另一种方法的方法

时间:2022-01-26 04:03:51

I'm new in js.

我是js的新手。

I see code example:

我看到代码示例:

foo.bar().baz()

How described foo bar and baz that we can call so?

如何描述foo bar和baz,我们可以这么称呼?

Thank you.

2 个解决方案

#1


8  

What are you are probably after is called chaining. A method can return the object it's running on this, so that another method may be called.

你可能追求的是被称为链接的东西。方法可以返回它在其上运行的对象,以便可以调用另一个方法。

var foo = {
  bar: function() {
    doStuff();
    return this;
  },

  baz: function() {
    doOtherStuff();
    return this;
  }
};

foo.bar().baz();

This is exactly how jQuery works, in order to allow things like:

这正是jQuery的工作原理,以便允许以下内容:

$('#foo')
  .html('<p>hi</p>')
  .addClass('selected')
  .css('font-size', '24px')
  .show();

#2


0  

So let's say you had an object foo with two methods: bar and bad. The implementation of bar would be like this: function bar() { /* do work */ return this; } That returns foo itself so you can call baz since it's defined in foo.

所以假设你有一个对象foo有两种方法:bar和bad。 bar的实现如下:function bar(){/ * do work * / return this;返回foo本身就可以调用baz,因为它是在foo中定义的。

#1


8  

What are you are probably after is called chaining. A method can return the object it's running on this, so that another method may be called.

你可能追求的是被称为链接的东西。方法可以返回它在其上运行的对象,以便可以调用另一个方法。

var foo = {
  bar: function() {
    doStuff();
    return this;
  },

  baz: function() {
    doOtherStuff();
    return this;
  }
};

foo.bar().baz();

This is exactly how jQuery works, in order to allow things like:

这正是jQuery的工作原理,以便允许以下内容:

$('#foo')
  .html('<p>hi</p>')
  .addClass('selected')
  .css('font-size', '24px')
  .show();

#2


0  

So let's say you had an object foo with two methods: bar and bad. The implementation of bar would be like this: function bar() { /* do work */ return this; } That returns foo itself so you can call baz since it's defined in foo.

所以假设你有一个对象foo有两种方法:bar和bad。 bar的实现如下:function bar(){/ * do work * / return this;返回foo本身就可以调用baz,因为它是在foo中定义的。