JS学习(慕课网)
只学,不记录,又不实战,很容易忘记的。所以想通过这个记录一下。视频链接
最近总遇到这种情况,这个好像写过,但忘了怎么写,查百度和自己写过的又不一样,这样就会浪费时间,所以经常记录也是值得的。此说明基于ES5。
pt() 代表输出:
function pt(a) {
console.log(a);
}
闭包(Closure)
优点:灵活方便、封装
缺点:空间浪费、内存泄漏、性能消耗
1.点击3个div,显示不同的数字
var te = document.getElementById('test');
//It can also be executed correctly without single quote.
te.innerHTML = "<div id=div1>aaa</div> <div id=div2>bbb</div> <div id='div3'>ccc</div>";
for(var i=1;i<4;i++) {
document.getElementById('div'+i).addEventListener('click', function(){
alert(i);
});
}
这样写会发现每次点击出现的都是4。我们可以用闭包来实现。
for(var i=1;i<4;i++) {
(function(i){
document.getElementById('div'+i).addEventListener('click', function(){
alert(i);
});
}) (i);
}
2.用闭包封装_userId等变量。
//closure package
(function() {
var _userId = 234;
var _typeId = 'item';
var sexport = {};
function converter(userId) {
return +userId;
}
sexport.getUserId = function() {
return converter(_userId);
}
sexport.getTypeId = function() {
return _typeId;
}
window.sexport = sexport;
}) ();
pt(sexport.getUserId());
pt(sexport.getTypeId());
pt(sexport._userId);
pt(sexport._typeId);
pt(sexport.converter);
作用域(Scope)
JS只有全局、函数、eval作用域,ES5没有块级作用域,ES6有了,用let声明,然而我看的视频是ES5的。
var a = 10;
(function() {
var b = 23;
}) ();
pt(a);
// pt(b); not defined
for(var item in {a:1, b:2}) {
pt(item);
}
pt(item);
eval("var a = 1;");
原型链(Prototype chain)
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.hi = function() {
console.log('Hi,my name is ' + this.name +" I'm " + this.age
+ ' years old now.');
};
Person.prototype.LEGS_NUM = 2;
Person.prototype.ARMS_NUM = 2;
Person.prototype.walk = function() {
console.log(this.name + ' is walking...');
}
function Student(name, age, className) {
Person.call(this, name, age);
this.className = className;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.hi = function() {
console.log('Hi,my name is ' + this.name +" I'm " + this.age
+ ' years old now,and from ' + this.className + '.');
}
Student.prototype.learn = function(subject) {
console.log(this.name + ' is learning ' + subject + ' at ' +
this.className + '.');
}
//test
var wen = new Student('zmy', 21, 'Class 1,Grade 3');
wen.hi();
wen.LEGS_NUM;
wen.walk();
wen.learn('programming');
prototype也是对象,那么就用可以更改。添加属性,已创建的对象可以访问;改变对象,新创建的对象可以访问。
//Add attributes to prototype, have an impact on the object has been created.
Student.prototype.x = 11;
console.log(wen.x); //11
Student.prototype = {y : 2};
console.log(wen.y); //undefined
console.log(wen.x); //11
//Change prototype, affect the newly created object.
var meng = new Student('Meng', 20, 'Class myLove')
console.log(meng.x); //undefined
console.log(meng.y); //2
定义属性,和检查是否有属性
//The other options is false
Object.defineProperty(obj, 'x', {
writable : true, value : 1
});
obj.hasOwnProperty('z');