<script type="text/javascript">//------------------Person类//(Person)的构造函数function Person(name, sex) {this.name = name;this.sex = sex;}Person.prototype.showName = function() {console.log(this.name)};Person.prototype.showSex = function() {console.log(this.sex)};//var obj = new Person("tangsan","男");//obj.showName();//------------------Worker类//(Worker)的构造函数function Worker(name, sex, job) {console.log(this) //this->是new出来的Woker对象//构造函数伪装://调用父级(Person)的构造函数 —— 1.为了继承属性Person.call(this, name, sex);this.job = job;}//原型链://2.原型来继承父级原型Worker.prototype = Person.prototype;Worker.prototype.showjob = function() {console.log(this.job)}var Workerobj = new Worker("流川枫", "女", "篮球员");Workerobj.showjob();</script>
继承:
父类的构造函数。
子类继承属性。
//(Worker)的构造函数function Worker(name, sex, job) {console.log(this) //this->是new出来的Woker对象//构造函数伪装://调用父级(Person)的构造函数 —— 1.为了继承属性Person.call(this, name, sex);this.job = job;}
继承父类的方法。
//原型链://2.原型来继承父级原型Worker.prototype = Person.prototype;
子类影响父类的问题:
console.log(Person.prototype.showjob);//输出://function () {// console.log(this.job)// }
引用:
钥匙,同一块区域的地址
记住,js里面所有的对象全是引用。
var arr1 = [1,2,3];var arr2 = arr1;//配钥匙arr2.push(4);console.log(arr2);//1234console.log(arr1);//1234
如果我不希望是一个引用,我希望我修改arr2的时候,arr1不受影响,怎么做呢?ex:
var arr1 = [1,2,3];var arr2 = [];for(var i in arr1){//把arr1里的东西复制一份到arr2中。arr2[i]=arr1[i];}arr2.push(4);console.log(arr2);//1234console.log(arr1);//123
继承父类的方法的代码修改为:
//原型链://2.原型来继承父级原型//Worker.prototype = Person.prototype;for (var i in Person.prototype) {Worker.prototype[i] = Person.prototype[i]; }
instanceof
instanceof
运算符用来测试一个对象在其原型链中是否存在一个构造函数的prototype
属性。
type of :....的类型
var arr1 = [1,2,3];console.log(arr1 instanceof Array);//trueconsole.log(arr1 instanceof Object);//true 所有的类都是Object的一个子类,从object继承来的
如果觉得《JS高级 - 面向对象5(继承 引用)》对你有帮助,请点赞、收藏,并留下你的观点哦!