javascript 讨论 - 9/4
欢迎来观看
哈哈,这是我最新的javascript的感悟,请大家多多指教,其中关于我认为还比较容易忘的地方,特地记录下来
object 和 function 的不同
google 解释: JavaScript functions are a special type of objects, called function objects. A function object includes a string which holds the actual code – the function body – of the function. The code is literally just a string.
这意思就是说function 是object 的 一种,没什么特别的区别,用String进行存储,
class和object的区别
Class 定义:
Classes are in fact “special functions”, and just as you can define function expressions and function declarations, the class syntax has two components: class expressions and class declarations.
example;
function Cat() {
this.name = “大毛”;
}
var cat1 = new Cat();
alert(cat1.name); // 大毛
参考link:
http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html
http://www.ruanyifeng.com/blog/2010/05/object-oriented_javascript_encapsulation.html
这种方法,我们可以看到有this, 与函数的区别在于使用了new, 然后()不再是invoke用的,其实这有个名字叫做构造函数,是特殊的函数
类的构造方法:
Cat.prototype.makeSound = function(){
alert(“喵喵喵”);
}
Class 和Object 的关系:
A class is a template for objects. A class defines object properties including a valid range of values, and a default value. A class also describes object behavior. An object is a member or an “instance” of a class.
我总觉得只需要object 就够了,class是object 一个省力气的方法,用就好了,强行区分反而有问题
,function 是一个object, var b=function(){}, 本来我们用变量都是直接a=b, c=b之类的,但是如果我们想要invoke,就必须b();
Namespace
这个是解决不同JavaScript file命名相同的变量,导致的问题,
方法是用object 来包裹所有的变量和函数, var object ={}
object.function ={}
object.var=…
然后就可以避开这个问题了
Closure
closure means it will still remain the space and memory,就是function a1( global ){
return{
function b(x){
x*global}
}
}
Immediatedly invoked Function
(function (name){ console.log("Hello "+name)})()-> it will invoke
and we can export the local one to global one, using (function(window){
var a=1;window.a=a;})(window) //so the it will changed to window object;
就是不要把相同的变量名暴露在window class 里面
暂时写到这了,大家加油一起学