js闭包初探

//给函数添加一些属性
function Circle(r) {
	// body...
	this.r = r;
}

Circle.PI = 3.14;
Circle.prototype.area = function(c) {
	// body...
	console.log("good");
	return Circle.PI*this.r*this.r;
};
var c = new Circle(2);
console.log(c.area());

//是声明一个变量,将一个函数当作值赋给变量
var Circle = function(){
	var obj = new Object();
	obj.PI = 3.14;

	obj.area = function(r){
		return this.PI*r*r;
	}
	return obj;
}
var c = new Circle();
console.log(c.area(3));

//这种方法使用较多,也最为方便。var obj = {}就是声明一个空的对象

var Circle = {
	"PI":3.14159,
	"area":function (r) {
		// body...
		return this.PI * r*r;
	}
}

console.log(Circle.area(4.0));



//
var observer = (function(){
	var observerList = [];
	return{
		add:function(obj){
			observerList.push(obj);
		},
		empty:function(){
			observerList=[];
		},
		getCount:function(){
			return observerList.length;
		},
		toString(){
			for (var i = 0; i < observerList.length; i++) {
				document.write(observerList[i]);
			}
		}
	}
})();
observer.add("马万林");
console.log(observer.getCount());

observer.add("马林子");
console.log(observer.getCount());

observer.toString();

猜你喜欢

转载自blog.csdn.net/qq_38340601/article/details/81014710