默认有这一行 } let ffaf = new foor(‘lilei‘
// 结构函数
function arr(name, text) {
this.name = name;
this.text = text;
this.class = ‘clo-1‘;
// return this,默认有这一行
}
let f = new arr(‘col-2‘, arr)
console.log(arr) //function arr()
// 结构函数-扩展
let a = {}
let b = new Object()
console.log(a = b) //Object { }
// 原型和原型链 - 5个原型法则
// 原型法则和示例:5条原型法则,原型法则是学习原型链的根本
// 1.所有的引用类型(数组,东西,函数),都具有东西特性,即可自由扩展属性,(除了null以外)
// 2.所有的引用类型(数组,东西,函数),都有一个_proto_(隐式原型)属性,属性值是一个普通的东西。
// 3.所有的函数,,都有一个prototype(显式原型)属性,属性值也是一个普通的东西。
// 4.所有的引用类型,(数组,东西,函数),_proto_属性值指向它的结构函数的prototype属性值。
// 5.当试图得到一个东西的属性时,如果这个东西自己没有这个属性,那么会去它的_proto_(即它的结构函数的prototype)中寻找。
let obj = {}
obj.a = 100
let arr1 = []
arr.a = 100
function fn() {}
fn.a = 100
console.log(obj.__proto__) //Object { }
console.log(arr1.__proto__) //Array []
console.log(fn.__proto__) //function ()
console.log(fn.prototype) //Object { … }
console.log(obj.__proto__ === Object.prototype) //true
// 结构函数
function foo(name,age){
this.name = name
}
foo.prototype.alertName = function(){
alert(this.name)
}
// 创建实例
let g = new foo(‘nihao‘);
g.printName = function(){
console.log(this.name)
}
g.printName()
g.alertName()
//原型和原型链-5个原型法则-增补二点
for (let item in f) {
// 高级浏览器已经在 for in 中屏蔽了来自原型的属性
// 但是这里建议大家还是加上这个判断,保证措施的健壮性
if (f.hasOwnProperty(item)) {
console.log(item)
}
}
// 结构函数
function Foo(name, age) {
this.name = name
}
Foo.prototype.alertName = function() {
alert(this.name)
}
// 创建实例
let d = new Foo(‘lilei‘)
d.printName = function() {
console.log(this.name)
}
// 测试
d.printName()
d.alertName()
d.toString() // 要去f.__proto__.__proto__中查找
// 原型和原型链-原型链-instanceof,用于判断引用类型属于哪个结构函数的要领
// f instanceof Foo 的判断逻辑是:f的__proto__一层一层往上,能否对应到Foo.prototype,再试着判断f instanceof Object
let arra = [];
arra instanceof Array
console.log(typeof arra)
// 原型链担任的样子
function Animk(){
this.eat = function(){
console.log("domfaf")
}
};
function Dog(){
this.fa = function(){
console.log("dog")
}
};
Dog.prototype = new Animk();
let hashiqi = new Dog();
console.log(hashiqi)
// 描述new一个东西的过程
// 创建一个新东西,this指向这个新东西,执行代码,即对this赋值,返回this
function foor(name, age){
this.name = name;
this.age = age;
this.class = "class-1"
// return this,默认有这一行
}
let ffaf = new foor(‘lilei‘, 18)
let f2 = new Foo(‘hanmeimei‘, 18)
console.log(ffaf,f2)
js的原型和原型链
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/33027.html