javascript 嵌套函数

本文探讨了JavaScript中嵌套函数的概念,展示了如何利用闭包返回函数指针,并且通过实例详细解释了如何使用闭包实现类的封装,包括私有属性的设置与获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

8.8.4. Nested Functions as Closures
1、执行嵌套函数(方法)
var x = "global";
function f() {
var x = "local";
function g() { alert(x); }
g();
}
f(); // Calling this function displays "local"

2、返回函数指针
// This function returns a function each time it is called
// The scope in which the function is defined differs for each call
function makefunc(x) {
return function() { return x; }
}

// Call makefunc() several times, and save the results in an array:
var a = [makefunc(0), makefunc(1), makefunc(2)];

// Now call these functions and display their values.
// Although the body of each function is the same, the scope is
// different, and each call returns a different value:
alert(a[0]()); // Displays 0
alert(a[1]()); // Displays 1
alert(a[2]()); // Displays 2
3、闭包(简单来讲,通过函数嵌套实现类的封装。即私有(private)属性需通过公用(public)方法赋值与取值。)


function makeProperty(o, name, predicate) {
var value; // This is the property value

// The setter method simply returns the value.
o["get" + name] = function() { return value; };

// The getter method stores the value or throws an exception if
// the predicate rejects the value.
o["set" + name] = function(v) {
if (predicate && !predicate(v))
throw "set" + name + ": invalid value " + v;
else
value = v;
};
}


// The following code demonstrates the makeProperty() method.

var o = {}; // Here is an empty object


// Add property accessor methods getName and setName()

// Ensure that only string values are allowed

makeProperty(o, "Name", function(x) { return typeof x == "string"; });

注意:predicate为函数指针。由于predicate定义为
function(x)
{
return typeof x== "string";
}
需写成predicate(参数)来调用;


o.setName("Frank"); // Set the property value
print(o.getName()); // Get the property value
o.setName(0); // Try to set a value of the wrong type


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值