Js随笔

mac2022-06-30  22

一、常见知识点总结

1、闭包

闭包的本质在于“闭”和“包”,即把一些变量封闭起来,使其它程序访问不到,同时把这个封闭的东西打成包甩出来,让大家可以直接用这个包(函数)。最典型的实现之一是对象(或类)的私有成员,

看几个例子:
function MyClass() { // 这是一个封闭在 MyClass 中的局部变量 var _name; // 这是一个甩出来的“包” this.getName = function() { return _name; }; // 这是另一个甩出来的“包” this.setName = function(name) { // 这保证了_name的第一个字母和空格后的第一个字母是大写 // 而且因为闭包的原因,_name 不可能被 MyCLass() 外的程序访问到 // 也就保证了上述命名规则的无例外执行 _name = name.replace(/^.|\s./g, function(s) { return s.toUpperCase(); }); }; } var p = new MyClass(); p.setName("james fancy"); console.log(p.getName()); // James Fancy function fun(){ //匿名函数可以访问fun的作用域,因此是一个闭包。 var name="vuturn"; return function(){ alert(name) //这会将全局变量局部化,避免全局污染。 } }

2、原型链

//原型链实现继承最常用方法:组合继承 function superType(name){ this.name = name; this.colors = ['red','green','black'] } superType.prototype.sayName = function(){ console.log(this.name); } function subType(name,age){ superType.call(this,name); //绑定作用域并继承属性,既可以用源属性,也创建属于自己的属性 this.age = age; } subType.prototype = new superType(); //源实例赋值给subType原型 subType.prototype.constructor = subType; //构造函数指向自己 subType.prototype.sayAge = function(){ console.log(this.age) } //实现 var instance1 = new subType('nico1',22); instance1.colors.push('white'); console.log(instance1.colors) instance1.sayName() instance1.sayAge() var instance2 = new subType('kobe',33); console.log(instance2.colors) instance2.sayName() instance2.sayAge()

一、常见js自定义封装

1、自定义alert

var _alert = window.alert; MyAlert = function(str) { var $container=$('<div class="field-tooltipWrap"><div class="field-tooltipInner"><div class="field-tooltip fieldTipBounceIn"><div class="zvalid-resultformat">'+str+'</div></div></div></div>'); $container.appendTo($("body")); setTimeout(function(){ $container.remove(); },1500); }; MyAlert.noConflict = function() { window.alert = _alert; }; window.alert = window.MyAlert = MyAlert;

转载于:https://www.cnblogs.com/mapleChain/p/11527293.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)