构造函数
其实,每一个函数都可以作为构造函数,但为了区分,我们规定构造函数函数名首字母大写。?
function Foo (name, age){
this.name = name;
this.age = age;
this.class = "class-1"
//return this; // 默认有这一行
}
var f = new Foo("zhangsan", 20);
原型规则
5条原型规则是学习原型链的基础。?
- 所有的引用类型(数组、对象、函数)(null 除外),都具有对象特性,即可自由扩展属性
- 所有的引用类型(数组、对象、函数),都有一个
_proto_属性
,属性值是一个普通的对象。(隐式原型) - 所有的函数,都有一个
prototype属性
,属性值是一个普通的对象。(显式原型) - 所有的引用类型(数组、对象、函数),
_proto_属性值
指向它的构造函数的prototype属性值
- 当试图获取一个对象的某个属性的值时,如果这个对象本身没有这个属性,那么会去它的_proto_(即它的构造函数的 prototype)中寻找。
function Foo (name, age){
this.name = name;
this.age = age;
this.class = "class-1"
//return this; // 默认有这一行
}
Foo.prototype.alertName = function () {
alert(this.name);
}
var f = new Foo("zhangsan", 20);
f.printName = function () {
console.log(this.name);
}
f.printName();
f.alertName();
应用:循环对象自身的属性
function Foo (name, age){
this.name = name;
this.age = age;
this.class = "class-1"
//return this; // 默认有这一行
}
Foo.prototype.alertName = function () {
alert(this.name);
}
var f = new Foo("zhangsan", 20);
f.printName = function () {
console.log(this.name);
}
f.printName();
f.alertName();
for(item in f){
// 高级浏览器已经在 for in 中 屏蔽了来自 原型的属性。
// 但是这里建议加上这个判断,保证程序的健壮性。
if(f.hasOwnProperty(item)) {
console.log(item);
}
}
原型链
function Foo (name, age){
this.name = name;
this.age = age;
this.class = "class-1"
//return this; // 默认有这一行
}
Foo.prototype.alertName = function () {
alert(this.name);
}
var f = new Foo("zhangsan", 20);
f.printName = function () {
console.log(this.name);
}
f.printName();
f.alertName();
f.toString();// 要去f._proto_._proto_ 中查找
console.log(f);
根据第五条原型规则,当 f 没有 toString 方法时,去它的 隐式原型里边查找,查找到了 Foo.prototype 属性,但是也没有 toString 方法,于是去 Foo.prototype 的隐式属性里边查找。
我们知道,function 也是 object , object 有一个 toString 方法。于是 在 Object.prototype 里边查找到了 toString 方法。
相关问题
如何准确判断一个变量是数组类型
[] instanceof Array // true
写一个原型链继承的例子
封装DOM查询操作
function Elem (id){
this.elem = document.getElementById(id);
}
Elem.prototype.html = function (val) {
var elem = this.elem;
if(val){
elem.innerHTML = val;
return this; // 链式操作
} else {
return elem.innerHTML;
}
}
Elem.prototype.on = function (type, fn) {
var elem = this.elem;
elem.addEventListener(type,fn);
//return this; // 链式操作
}
var div1 = new Elem("s_wrap");
div1.html("<p>Hello world!</p>");
div1.on("click",function(){
alert("clicked!");
});
// 链式操作
//div1.html("<p>Hello world!</p>").on("click",function(){
// alert("clicked!");
//}).html("<p>点击过了!<p/>");
这个有点难以理解的话,且看下面这个 例子:
// 动物
function Animal() {
this.eat = function () {
console.log("animal eat!");
}
}
// 狗
function Dog () {
this.bark = function () {
console.log("dog bark!");
}
}
Dog.prototype = new Animal();
// 哈士奇
var hashiqi = new Dog();
console.log(hashiqi);
面试时千万不要说这个,说上面那一个啦!逼格更高点!?
描述 new 一个对象的过程
考点:对构造函数的理解
创建一个新对象 ⇨ this 指向这个新对象 ⇨ 执行代码,即是对 this 赋值 ⇨ 返回 this
zepto(或其他框架)源码中如何使用原型链
题外话:阅读源码 是高效提高技能的方式,要有“技巧”地阅读,慕课搜索“zepto设计和源码分析”
也没有说答案!心酸!?