如何在 jquery 函数中查找引用对象

how to find referred object in a jquery function

如何让 this.V2 脱离 FN 范围!?

$.fn.myFN = function(X){
  this.V1 = X;
  this.V2 = X+2;
};

$("#foo1").myFN(10);
$("#foo2").myFN(20);

console.log(  $("#foo2").V2  ) // this returned undefined 

您可以使用 .prop 将值存储在 DOM 元素中:

$.fn.myFN = function(X){
  $this = $(this);
  $this.prop('v1', X);
  $this.prop('v2', X+2);
};

$("#foo1").myFN(10);
$("#foo2").myFN(20);

console.log(  $("#foo2").prop('v2')  ) //=> 22

要按照您要求的方式进行操作,您需要 return this 从插件功能

$.fn.myFN = function (X) {
    this.V1 = X;
    this.V2 = X + 2;
    return this;
};


$(function () {
    var f1 = $("#foo1").myFN(10).V2,
        f2 = $("#foo2").myFN(20).V2;        

    console.log([f1, f2]) //logs [12,22]    
});

DEMO

Return $(this) 当前上下文

$.fn.myFN = function (X) {
    $(this).V1 = X;
    $(this).V2 = X + 2;
    return $(this);
};