美文网首页
Javascript中Function对象的属性和方法

Javascript中Function对象的属性和方法

作者: Observer_____ | 来源:发表于2018-03-12 01:15 被阅读0次

1. 属性(Properties)

  • arguments
    获取实际传递给函数的参数,类似数组,可以用arguments[n]来访问单个参数的值,是Object的实例而不是Array的实例。
function testArg(a, b) {
    var actCount = arguments.length,
        expCount = testArg.length,
        result;

    result = "Expected arguments' count is " + expCount + ";<br/>";
    result += "Actual arguments' count is " + actCount + ".<br/>";
    result += "They are:<br/>";
    for (var i = 0; i < actCount; i++) {
        result += arguments[i] + ";<br/>";
    }
    if (arguments instanceof Array) {
        result += "arguments is an Array instance."
    } else if (arguments instanceof Object) {
        result += "arguments is an Object instance."
    }
    document.write(result);
}
testArg(1);
//output result is:
Expected arguments' count is 2;
Actual arguments' count is 1.
They are:
1;
arguments is an Object instance.
  • length
    获取函数【定义】的参数个数

functionName.length

  • caller
    获取调用当前函数的函数。caller属性只有当函数正在执行时才被定义。

functionName.caller

如果函数是从 JavaScript 程序的顶层调用的,则caller包含null。如果在字符串上下文中使用 caller 属性,则其结果和 functionName.toString 相同,也就是说,将显示函数的反编译文本。

function test() {
    if (test.caller == null) {
        document.write("test is called from the toppest level");
    } else {
        document.write("test is called from the function:<br/>");
        document.writeln(test.caller.toString());
    }
    document.write("<br />");
}
//call from the top level
test();
//output: test is called from the toppest level

function testOuter() {
    test();
}

//call from the function testOuter
testOuter();
//output:
//test is called from the function:
//function testOuter() { test(); }
  • callee
    返回正被执行的 Function 对象,即指定的 Function 对象的正文。

[functionName.]arguments.callee

callee 属性是 arguments 对象的一个成员,该属性仅当相关函数正在执行时才可用。通常这个属性被用来递归调用匿名函数。

var fac = function(n){
  if (n <= 0)
     return 1;
  else
     return n * arguments.callee(n - 1);
}(4);
document.write(fac);//24
  • constructor
    获取创建某个对象的函数。constructor是每个具有原型的对象的原型成员。这包括除Global和Math对象之外的所有JavaScript内部对象。constructor属性就是用来构造对象实例的函数引用。
// A constructor function.
function MyObj() {
    this.number = 1;
}

var x = new String("Hi");

if (x.constructor == String)
    document.write("Object is a String.");
document.write ("<br />");

var y = new MyObj;
if (y.constructor == MyObj)
    document.write("Object constructor is MyObj.");

// Output:
// Object is a String.
// Object constructor is MyObj.
  • prototype
    获取对象的原型。每一个构造函数都有一个prototype属性,指向另一个对象。这个对象的所有属性和方法,会被构造函数的实例继承。也就是说,我们可以把那些不变的属性和方法定义在prototype对象上。
function Man(name, age) {
    this.name = name;
    this.age = age;
}
Man.prototype.sex = "M";
Man.prototype.struggle = function () {
    alert("day day up!!!!");
}
var li = new Man("Leo", 10);
alert(li.sex);//M
li.struggle();//day day up
Man.prototype.isStrong = true;
alert(li.isStrong);//true

同样可以在已定义好的对象(包括js的原生对象)中追加方法和属性。

var a = new Number(2);
console.log(typeof(a.add);  // undefined
Number.prototype.add = function (add1) {
  return this+add1;
}
alert(aa.add(1)); // 3

2. 方法(Properties)

  • apply
    调用函数,并用指定对象替换函数的this值,同时用指定数组替换函数的参数。

functionName.apply([thisObj], [,argArray]);

如果argArray为无效值,则会抛出"Object expected"错误;如果thisObj和argArray都没有提供,则会使用当前this作为thisObj

function callMe(arg1, arg2) {
    var s = "";

    s += "this value: " + this;
    s += "<br />";
    for (i in callMe.arguments) {
        s += "arguments: " + callMe.arguments[i];
        s += "<br />";
    }
    return s;
}

document.write("Original function: <br/>");
document.write(callMe(1, 2));
document.write("<br/>");

document.write("Function called with apply: <br/>");
document.write(callMe.apply(3, [4, 5]));
document.write("<br/>");

document.write("Function called with apply with invalid array: <br/>");
try{
    document.write(callMe.apply(3,2));
} catch (e) {
    document.write(e.message);
}
document.write("<br/><br/>");

document.write("Function called with apply without any argument: <br/>");
document.write(callMe.apply());
//Output result:
//Original function: 
//this value: [object Window]
//    arguments: 1
//    arguments: 2

//Function called with apply: 
//this value: 3
//    arguments: 4
//    arguments: 5

//Function called with apply with invalid array: 
//Function.prototype.apply: Arguments list has wrong type

//Function called with apply without any argument: 
//this value: [object Window]
  • call
    调用一个对象的方法,用另一个对象替换当前对象。

call([thisObj[, arg1[, arg2[, [, argN]]]]])

它允许您将函数的 this 对象从初始上下文变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,则 global 对象被用作 thisObj。与apply方法唯一不同的地方是,apply的第二个参数类型必须是Array,而call方法是将所有的参数列举出来,用逗号分隔。

function callMe(arg1, arg2){
    var s = "";

    s += "this value: " + this;
    s += "<br />";
    for (i in callMe.arguments) {
        s += "arguments: " + callMe.arguments[i];
        s += "<br />";
    }
    return s;
}

document.write("Original function: <br/>");
document.write(callMe(1, 2));
document.write("<br/>");

document.write("Function called with call: <br/>");
document.write(callMe.call(3, 4, 5));

// Output: 
// Original function: 
// this value: [object Window]
// arguments: 1
// arguments: 2

// Function called with call: 
// this value: 3
// arguments: 4
// arguments: 5
  • bind
    对于给定函数,创建具有与原始函数相同的主体的绑定函数。在绑定功能中,this对象解析为传入的对象,该绑定函数具有指定的初始参数。

function.bind(thisArg[, arg1[ ,arg2[, argN]]);

其中function和thisArg为必选项,返回一个与function函数相同的新函数,只是this对象和参数不同。

// Define the original function.
var checkNumericRange = function(value) {
  if (typeof value !== 'number') {
    return false;
  } else {
    return value >= this.minimum && value <=this.maximum;
  }
}
// The range object will become the this value in the callback function.
var range = {minimum:10, maximum:20};

// Bind the checkNumericRange function.
var boundCheckNumericRange = checkNumericRange.bind(range);

// Use the new function to check whether 12 is in the numeric range.
var result = boundCheckNumericRange (12);
document.write(result);

// Output: true

以下代码演示如何使用 arg1[,arg2[,argN]]] 参数。 该绑定函数将 bind 方法中指定的参数用作第一个参数和第二个参数。 在调用该绑定函数时,指定的任何参数将用作第三个、第四个参数(依此类推)。

// Define the original function with four parameters.
var displayArgs = function (val1, val2, val3, val4) {
    document.write(val1 + " " + val2 + " " + val3 + " " + val4);
}

var emptyObject = {};

// Create a new function that uses the 12 and "a" parameters
// as the first and second parameters.
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");

// Call the new function. The "b" and "c" parameters are used
// as the third and fourth parameters.
displayArgs2("b", "c");
// Output: 12 a b c

在对象定义内部使用bind方法可以将某个事件绑定到对象内部的某个方法,

<input type="button" id="start" value="Start" />
<input type="button" id="stop" value="Stop" />
<script type="text/javascript">
    function Car(owner) {
        this.owner = owner;
        this.start = function () {
            //start the car
            console.log(this);
            //output: Car {owner: "Mike", start: function, stop: function} check.html:14
            console.log(this.owner + "'s car is starting.");
            //output: Mike's car is starting. 
        };
        this.stop = function () {
            console.log(this);
            //output: <input type="button" id="stop" value="Stop" />
            console.log(this.owner + "'s car is starting.");
            //output: undefined's car is stopping.
        };
    }
    var btnStart = document.getElementById("start"),
        btnStop = document.getElementById("stop"),
        someCar = new Car("Mike");

    if (document.attachEvent) {
        btnStart.attachEvent("onClick", someCar.start.bind(someCar));
        btnStop.attachEvent("onClick", someCar.stop);
    } else if (document.addEventListener) {
        btnStart.addEventListener("click", someCar.start.bind(someCar), false);
        btnStop.addEventListener("click", someCar.stop, false);
    }
</script>

从上面Sample我们发现,当不使用bind方法的时候,事件里面的this指向的触发click事件dom元素input,它当然没有owner属性;如果利用bind指定事件里面的this对象,就能达到我们想要的效果。

相关文章

网友评论

      本文标题:Javascript中Function对象的属性和方法

      本文链接:https://www.haomeiwen.com/subject/jjpgfftx.html