js面向对象编程
js中没有类的概念,但是却能够创建对象,并实现继承,封装,多态的特点。
因为在js中所有的函数既可以当成是构造函数,也可以当成普通函数调用,当函数当成构造函数调用时,该函数就可以被当成所有对象的基类。
封装
function shape(name) {
this.name = name;
this.toString = function (){
return this.name;
}
}
属性和方法都封装在构造函数中,创建对象的时候对象的时候,对象中也能够访问这些方法和属性。
var myShape = new shape('myshape');
1: js中准确判断数据类型
Object.prototype.toString.call(var).slice(8,-1).toLowerCase()
返回值”object”,”array”,”function”,”null”,”undefined”,”string”,”number”,”boolean”
2:js 中f.prototype.constructor = f用法的原理
function Dog(name) {
this.name = name;//私有属性
}
Dog.prototype.say = function() {
alert(this.name);
}
var dog1 = new Dog('豆豆');
dog1能访问到Dog构造函数和原型中定义的方法和属性。
此时重写Dog.prototype,
Dog.prototype = {
hair: true,
tags: true
}
var dog2 = new Dog('萌萌');
那么dog1不能访问新的原型中的方法和属性,dog2能访问新的原型中的方法和属性,但是不能访问之前定义的方法和属性,而且此时
dog3.constructor ->
function Object() { [native code]}
dog1.constructor ->
function Dog(name) {
this.name = name;
}
要想让
dog3.constructor ->
function Dog(name) {
this.name = name;
}
解决方法是
Dog.prototype.constructor = Dog;
–未完待续
还没有评论,来说两句吧...