一、原型共享
function inherit(target, origin){
function F(){};
F.prototype = origin.prototype;
target.prototype = new F();
target.prototype.constructor = target; //target的直接构造器是谁
target.prototype.super = origin.prototype;
}
var inherit = (function(){
var F = function(){};
return function(target, origin){
F.prototype = origin.prototype;
target.prototype = new F();
target.prototype.constructor = target; //target的直接构造器是谁
target.prototype.super = origin.prototype;
}
})();
Zhang.prototype.lastName = "zhangsan";
function Zhang(){}
function Li(){}
//Li.prototype = Zhang.prototype;
inherit(Li, Zhang);
var lisi = new Li();
var zhangsan = new Zhang();
Li.prototype.age = "20";
二、闭包
function test(){
var num = 1;
function demo(){
console.log(num);
var a = 2;
return function(){
console.log(a);
}
}
return demo;
}
var b = test();
b();
function test(){
var arr = [];
for(var i = 0; i < 10; i++){
(function(i){
arr[i] = function(){
console.log(i);
}
}(i));
}
return arr;
}
var returnArr = test();
for(var j = 0; j < returnArr.length; j++){
returnArr[j]();
}
var li = document.getElementsByTagName("li");
for(var i = 0; i < li.length; i++){
li[i].onclick = function(){
console.log(i);
}
}
三、命名空间
var name = "123";
var init = (function(){
var name = "zhangsan";
function callname(){
f();
console.log(name);
};
function f(){}
return function(){
callname();
}
}());
var initLi = (function(){
var name = "lisi";
function callname(){
f();
console.log(name);
};
function f(){}
return function(){
callname();
}
}());
四、链式调用
var zhangsan = {
smoke:function(){
console.log("smoking");
return this;
},
drink:function(){
console.log("drinking");
return this;
}
}
zhangsan.smoke().drink();
五、访问属性的两种方法
var obj = {
name : "zhangsan"
}
console.log(obj.name)
console.log(obj["name"]);
var Zhangsan = {
girlFriend1:"xiaozhang",
girlFriend2: "xiaowang",
girlFriend3: "xiaomeng",
sayGirlFriend : function(num){
console.log(this["girlFriend"+num]);
}
}
六、对象枚举-各种方法
var arr = [1, 2, 3, 4, 5, 6, 7 ,8];
for(var i = 0; i < arr.length; i++){
console.log(arr[i]);
}
var obj = {
name : 123,
age : 100,
height : 180,
weight : 200,
__proto__ : {
lastName : "abc"
}
}
for(var key in obj){
console.log(key + " " + typeof(key));
console.log(obj.key);
if(obj.hasOwnProperty(key)){ //去除原型链上的属性
console.log(obj[key]);
}
}
//A instanceof B 构造出来的
//A 对象的原型链上没有B的原型
function Person(){
}
var person = new Person();
for(var prop in window){
console.log(prop);
console.log(window[prop]);
}
var div = document.getElementById("box");
for(var key in div){
console.log(key + " : " + div[key]);
}
网友评论