JavaScript学习笔记1

var point = {x:10,y:10};
point.r = function(){
return Math.sqrt()
}

function cat(name,color){
return {
name:name,
color:color
}
}

var cat1 = cat("tom","yellow");
var cat2 = cat("jim","black");

// 所谓"构造函数",其实就是一个普通函数,但是内部使用了this变量。
// 对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。
function dog(name,color){
this.name = name;
this.color = color;
}

var dog1 = new dog("ww","white");
var dog2 = new dog("www","gray");

//这时dog1和dog2会自动含有一个constructor属性,指向它们的构造函数。

console.log("constructor " + (dog1.constructor == dog));//true

for(attr in dog1)
{
console.log("dog1 attr :" + attr);
}

//验证原型对象与实例对象之间的关系
console.log("instanceof: " + (dog1 instanceof dog));//true


// Javascript规定,每一个构造函数都有一个prototype属性,指向另一个对象。
// 这个对象的所有属性和方法,都会被构造函数的实例继承。
//这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上。
function Dog(name)
{
this.name = name;
}
Dog.prototype.type = "犬科";
Dog.prototype.eat = function(food){console.log("eating " + food);}//eat定义的时候不需要括号;
var dog3 = new Dog();
dog3.eat("bone")//调用eat的时候必须要括号,即使是无参方法
var dog4 = new Dog();
console.log(dog4.eat == dog3.eat);//true
//isPrototypeOf() 判断prototype对象与某个实例之间的关系
console.log("is prototype " + Dog.prototype.isPrototypeOf(dog3));
//hasOwnProperty() 每个实例都有一个hasOwnProperty()方法,判断某一属性到底是本地属性,
//还是继承自prototype属性(Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。)指向的对象的属性。

posted @ 2016-01-04 22:56  jht_newbie  阅读(144)  评论(0编辑  收藏  举报