1.字面量创建 对象是由属性和方法组成的
var obj = {
"属性名":属性值
"方法名":function(){}
}
2.使用new 关键字创建
var obj = new Object();
//给obj添加属性和方法
obj.name = "zs"
obj.skill = function(){}
3.工厂模式创建
function fun1(name,age){
var obj = new Object();
obj.name = name
obj.age = age
obj,eat = function(){}
return obj
}
4.构造函数创建
function Fun(name,age){
this.name = name;
this.age = age
}
//实例化对象(调用构造函数)
new Fun("zs",20)
5.原型创建
prototype原型:每创建构造函数 都会自带一个prototype 用于存储共享的属性和方法
__proto__原型属性:每创建实例化对象 都有自带一个__proto__ 然__proto__指向构造函数的prototype
function Fun(){}
Fun.prototype.name = "ls"
FUn.prototype.skill = function(){}
var a = new Fun();
console.log(a.__proto__)
a.__proto__.name = ls
6.混合创建(构造函数(传参)+原型(不传参))
// 学号 姓名 年龄 性别 skill
function FUn(classid,name,age,sex){
this.classid = classid
this.name = name
this.age = age
this.sex = sex
}
Fun.prototype.skill = function(){
console.log("好好学习")
}
new Fun(1,"zs",20,"男")
//原型链:当你创建构造函数和实例化对象的时候 自动形成的一种查找关系
//先找自己 找自己的__proto__ 去找构造函数 还找不到undefined
this的指向 this在不同的场景指向不同
事件处理函数中 this当前触发事件的对象(标签)
在普通函数中 this指向window
在方法中,this指向方法所在的对象
在构造函数中 this指向实例化对象
改变this的指向
call(this的新指向,参数1,参数2.。。。。)
apply(this的新指向,[参数1,参数2....])
检测数据类型
typeof
Object.prototype.toString.call(检测数据)
instansof 检测当前内容是否由某个构造函数创建
面向对象的选项卡
<script>
// var btn = document.getElementsByTagName("button");
// var odiv = document.getElementsByTagName("div");
// for(var i = 0;i<btn.length;i++){
// btn[i].index =i;
// btn[i].onclick = function(){
// for(var j = 0;j<odiv.length;j++){
// odiv[j].style.display = "none";
// }
// odiv[this.index].style.display = "block";
// }
// }
/*
面向对象的选项卡
创建面向对象构造函数 面向对象都是由属性和方法组成的
标签作为对象的属性 点击事件和for循环作为对象的方法
*/
function SwitchTab() {
// 添加属性
this.btn = document.getElementsByTagName("button");
this.odiv = document.getElementsByTagName("div");
var that = this;// 在这里this还是指向实例化对象的
// 入口方法 添加方法
this.init = function () {
for (var i = 0; i < this.btn.length; i++) {
this.btn[i].index = i;
this.btn[i].onclick = function () {
// console.log(this);//在事件处理函数中 this指向当前触发事件的对象
// 如何让this指向实例化对象
that.changeItem(this.index);//想让this指向实例化对象
}
}
}
// 入口方法调用
this.init();
this.changeItem = function (index) {
for (var j = 0; j < this.odiv.length; j++) {
this.odiv[j].style.display = "none";
}
// this.index 想让this指向触发对象 但是现在这个this指向实例化对象
this.odiv[index].style.display = "block";
}
}
// 实例化对象
new SwitchTab();
</script>