美文网首页
[JavaScript基础] 继承模式 命名空间 对象枚举

[JavaScript基础] 继承模式 命名空间 对象枚举

作者: Darkdreams | 来源:发表于2018-12-26 12:43 被阅读0次

继承模式

圣杯模式

function Father(){
}
function Son(){
}

function extend(Child, Parent) {
    var F = function() {}
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.prototype.uber = Parent.prototype;
}

extend(Son, Father);
var son = new Son();
var father= new Father();

Yahoo YUI库

var inherit  = (function() {
  var F = function () {};
  return function(Child, Parent) {
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.prototype.uber = Parent.prototype;
  }
}())

命名空间

链式调用(模拟jQuery)

实现方法的连续调用,return this

var obj = {
  one : function() {
    console.log("one");
    return this; 
  },
  two: function() {
    console.log("two");
    return this; 
  },
  three: function() {
    console.log("three");
    return this; 
  }
}
obj.one().two().three();   // one two three

访问属性

var obj = {
  name : "ABC"
}
// 第一种
console.log(obj.name)
// 第二种
console.log(obj["name"])  //注:中括号里面必须是字符串

//obj.name  ====> 在执行时会隐式转化为obj["name"]
//小例子
var student = {
    number1: "TOM",
    number2: "JIM",
    number3: "ROY",
    number4: "JOHN",
    sayNumber : function(num) {
        return this["number" + num]
    }
}
console.log(student.sayNumber(1))  // TOM
....

对象枚举

for in

var obj = {
 name : "tom",
 age : 123,
 sex: "male",
 class: 3,
 sports: function() {
    console.log("baseball")
 }
}
for (var key in obj) {
 console.log(typeof key) //类型是String字符串
 console.log(obj.key) 
// 切记不要这么获取,这样是获取obj对象下的key属性,并不是对象遍历后的所有属性。
// 在底层,会隐式把obj.key ===> 转换成obj["key"]
 console.log(obj[key])  //正确,但中括号不需要加引号,因为key的类型就已经是字符串了。
}

hasOwnProperty
判断属性是否是对象自己本身的属性,返回布尔值
[object].hasOwnProperty([属性名])属性名是字符串

var obj = {
    name : "tom",
    age : 123,
    sex: "male",
    class: 3,
    sports: function() {
        console.log("baseball")
    },
    __proto__ : {
        familyName : "Brand"
    }
}
for (var key in obj) {
    if(obj.hasOwnProperty(key)) {
        console.log(obj[key])
    }
}

in
判断属性是不是对象中的。返回布尔值

sex in obj  //报错
//属性名一定要写成字符串
"sex" in obj  //正确

instanceof
检测对象是否是构造函数构造出来的,返回布尔值
语法:[Object 对象] instanceof [某构造函数 constructor]
A instanceof B
A的原型链上有没有B的原型

相关文章

网友评论

      本文标题:[JavaScript基础] 继承模式 命名空间 对象枚举

      本文链接:https://www.haomeiwen.com/subject/pimkkqtx.html